Pressing a button in my iOS app calls the changeLanguage method.
- (void)changeLanguage:(BOOL) isMyanmar {
if (hasRun == YES) {
return;
}
hasRun = YES;
NSUserDefaults * userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setBool:isMyanmar forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self countDown];
}
- (void)countDown {
static int i = 3;
if (i == 3) {
i--;
UIImage *three = [UIImage imageNamed:#"Three"];
countDownFlag = [[UIImageView alloc] initWithImage:three];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
[self.view addSubview:countDownFlag];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 2) {
i--;
UIImage *two = [UIImage imageNamed:#"Two"];
[countDownFlag setImage:two];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 1) {
i--;
UIImage *one = [UIImage imageNamed:#"One"];
[countDownFlag setImage:one];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
The method used to run fine but recently is having trouble with threading at [self countDown].
What could be causing the problem and how can I resolve this?
Edit:
How changeLanguage gets called
Two methods call this method:
- (void)changeLanguageToEnglish {
[self changeLanguage:false];
}
- (void)changeLanguageToMyanmar {
[self changeLanguage:true];
}
How the button calls the methods:
[languageButton addTarget:self action:#selector(changeLanguageToEnglish) forControlEvents:UIControlEventTouchUpInside];
Related
Hi there all the past couple days now I’ve been trying to modify the iOS tweak Daisy. I have successfully added more fonts, make the Hello animation stay on the screen and merged a closed pull request that the original dev didn’t want In. Anyways I’m up to trying to fix this bug that the original version has and that is that the “playHelloStartAnimation” will bug out sometimes when waking the phone. Sometimes it will fully replay the animation from the beginning or a couple frames from the middle of the animation, other times it will finish and show nothing for a few millisecond and then continue to the next animation or will play as intended. Tried adding a blank animation to play first so when it dose bug out you’ll won’t see but didn’t help, change times, tried other hooks still happens. Can’t figure out why any help would be appreciated.
%group DiaryHello
%hook CSCoverSheetView
%property(nonatomic, retain)UIView* diaryHelloIconView;
%property(nonatomic, retain)UILabel* diaryHelloLabel;
- (void)didMoveToWindow { // add iphone hello
%orig;
// hello label
if (enableHelloSwitch && showHelloGreetingSwitch && ![self diaryHelloLabel]) {
self.diaryHelloLabel = [UILabel new];
[[self diaryHelloLabel] setTextColor:[UIColor whiteColor]];
if ([fontFamilyValue intValue] == 0) [[self diaryHelloLabel] setFont:[UIFont fontWithName:#"Selawik-Regular" size:24]];
else if ([fontFamilyValue intValue] == 1) [[self diaryHelloLabel] setFont:[UIFont systemFontOfSize:24 weight:UIFontWeightRegular]];
[[self diaryHelloLabel] setText:greetingValue];
[[self diaryHelloLabel] setTextAlignment:NSTextAlignmentCenter];
[[self diaryHelloLabel] setAlpha:0];
[[self diaryHelloLabel] setHidden:YES];
[self addSubview:[self diaryHelloLabel]];
[[self diaryHelloLabel] setTranslatesAutoresizingMaskIntoConstraints:NO];
[NSLayoutConstraint activateConstraints:#[
[self.diaryHelloLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:150],
[self.diaryHelloLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
[self.diaryHelloLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
]];
}
}
%new
- (void)initHelloViewWithAnimation:(int)animation { // set hello view up
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
[[self diaryHelloIconView] stopAnimating];
[[self diaryHelloIconView] removeFromSuperview];
self.diaryHelloIconView = nil;
if (animation == 0) {
helloStartArray = [NSMutableArray new];
for (int i = 0; i < 24; i++) [helloStartArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/start/%i.png", i]]];
helloStartImage = [UIImage animatedImageWithImages:helloStartArray duration:0.6];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloStartImage];
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
} else if (animation == 1) {
helloSearchingArray = [NSMutableArray new];
for (int i = 0; i < 116; i++) [helloSearchingArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/searching/%i.png", i]]];
helloSearchingImage = [UIImage animatedImageWithImages:helloSearchingArray duration:4.28];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloSearchingImage];
helloStartArray = nil;
helloStartImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
} else if (animation == 2) {
helloAuthenticatedArray = [NSMutableArray new];
for (int i = 0; i < 51; i++) [helloAuthenticatedArray addObject:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"/Library/PreferenceBundles/DiaryPreferences.bundle/hello/authenticated/%i.png", i]]];
helloAuthenticatedImage = [UIImage animatedImageWithImages:helloAuthenticatedArray duration:1.12];
self.diaryHelloIconView = [[UIImageView alloc] initWithImage:helloAuthenticatedImage];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
}
[[self diaryHelloIconView] setContentMode:UIViewContentModeScaleAspectFit];
[[self diaryHelloIconView] setClipsToBounds:YES];
[[self diaryHelloIconView] setHidden:NO];
if (![[self diaryHelloIconView] isDescendantOfView:self]) [self addSubview:[self diaryHelloIconView]];
[[self diaryHelloIconView] setTranslatesAutoresizingMaskIntoConstraints:NO];
[NSLayoutConstraint activateConstraints:#[
[self.diaryHelloIconView.topAnchor constraintEqualToAnchor:self.topAnchor constant:50],
[self.diaryHelloIconView.centerXAnchor constraintEqualToAnchor:self.centerXAnchor],
[self.diaryHelloIconView.heightAnchor constraintEqualToConstant:80],
[self.diaryHelloIconView.widthAnchor constraintEqualToConstant:80],
]];
}
%new
- (void)playHelloStartAnimation { // play hello start animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
shouldPlaySearchAnimation = YES;
[self initHelloViewWithAnimation:0];
[[self diaryHelloIconView] setAnimationRepeatCount:1];
[[self diaryHelloIconView] startAnimating];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self playHelloSearchingAnimation];
});
}
%new
- (void)playHelloSearchingAnimation { // play hello searching animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
if (!shouldPlaySearchAnimation) return;
[self initHelloViewWithAnimation:1];
[[self diaryHelloIconView] setAnimationRepeatCount:0];
[[self diaryHelloIconView] startAnimating];
if (showHelloGreetingSwitch) [[self diaryHelloLabel] setAlpha:0];
}
%new
- (void)playHelloAuthenticatedAnimation { // play hello authenticated animation
if (!enableHelloSwitch) return;
if (enableMediaPlayerSwitch && ![[self diaryPlayerView] isHidden]) return;
shouldPlaySearchAnimation = NO;
[self initHelloViewWithAnimation:2];
[[self diaryHelloIconView] setAnimationRepeatCount:1];
[[self diaryHelloIconView] startAnimating];
if (showHelloGreetingSwitch) {
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
[UIView animateWithDuration:0.25 delay:0.4 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[[self diaryHelloLabel] setHidden:NO];
[[self diaryHelloLabel] setAlpha:1];
[notificationCenter postNotificationName:#"diaryUpdateNotificationList" object:nil];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[[self diaryHelloLabel] setAlpha:0];
} completion:^(BOOL finished) {
[[self diaryHelloIconView] setHidden:YES];
[[self diaryHelloLabel] setHidden:YES];
[[self diaryHelloIconView] removeFromSuperview];
[notificationCenter postNotificationName:#"diaryUpdateNotificationList" object:nil];
}];
}];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.8 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[[self diaryHelloIconView] setHidden:YES];
[[self diaryHelloIconView] removeFromSuperview];
[[NSNotificationCenter defaultCenter] postNotificationName:#"diaryUpdateNotificationList" object:nil];
});
}
}
%end
%hook CSCoverSheetViewController
- (void)viewDidDisappear:(BOOL)animated { // remove hello view when lock screen disappeared
%orig;
// free up memory when hello is not visible
[[coverSheetView diaryHelloIconView] stopAnimating];
[[coverSheetView diaryHelloIconView] removeFromSuperview];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
}
%end
%hook SBLockScreenManager
- (void)lockUIFromSource:(int)arg1 withOptions:(id)arg2 { // remove hello view when device was locked
%orig;
// free up memory when hello is not visible
isLockedHello = YES;
isScreenOnHello = NO;
[[coverSheetView diaryHelloIconView] stopAnimating];
[[coverSheetView diaryHelloIconView] removeFromSuperview];
helloStartArray = nil;
helloStartImage = nil;
helloSearchingArray = nil;
helloSearchingImage = nil;
helloAuthenticatedArray = nil;
helloAuthenticatedImage = nil;
}
%end
%hook SBBacklightController
- (void)turnOnScreenFullyWithBacklightSource:(long long)arg1 { // update diary when screen turns on
%orig;
if (![[%c(SBLockScreenManager) sharedInstance] isLockScreenVisible]) return; // this method gets called not only when the screen gets turned on, so i verify that it was turned on by checking if the lock screen is visible
if (!isScreenOnHello) [coverSheetView playHelloStartAnimation];
[[NSNotificationCenter defaultCenter] postNotificationName:#"diaryUpdateNotificationList" object:nil];
isScreenOnHello = YES;
}
%end
%hook SBDashBoardBiometricUnlockController
- (void)setAuthenticated:(BOOL)arg1 { // play authenticated animation when unlocked with biometrics
%orig;
if (arg1 && isLockedHello) {
isLockedHello = NO;
[coverSheetView playHelloAuthenticatedAnimation];
}
}
%end
%end
Original tweaks source code: https://github.com/schneelittchen/Diary
I have a modal view in which a countdown starts when the user had performed some action. At the end of the countdown, the modal view would close. The following is the procedure I have written towards that goal but unfortunately, it is causing some thread problems. Is there any way to rewrite this in a way that does not have potential thread issues?
- (void)countDown {
static int i = 3;
if (i == 3) {
i--;
UIImage *three = [UIImage imageNamed:#"Three"];
countDownFlag = [[UIImageView alloc] initWithImage:three];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
[self.view addSubview:countDownFlag];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 2) {
i--;
UIImage *two = [UIImage imageNamed:#"Two"];
[countDownFlag setImage:two];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 1) {
i--;
UIImage *one = [UIImage imageNamed:#"One"];
[countDownFlag setImage:one];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
Edit: the picture shows what XCode tells me about the problem
More edit:
My code has changed to reflect vadian's answer. Here is the update
- (void)startCountDown {
NSLog(#"starting count down");
counter = 3;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
- (void)countDown:(NSTimer *)timer {
if (counter == 3) {
countDownFlag = [[UIImageView alloc] init];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:countDownFlag];
});
} else if (counter == 0) {
[timer invalidate];
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
NSArray *imageNameArray = #[#"", #"One", #"Two", #"Three"];
UIImage *image = [UIImage imageNamed:imageNameArray[counter]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.countDownFlag setImage:image];
});
counter--;
}
I new guess that the problem probably lies in the code that calls the countdown. Here is the code that does this.
- (void)changeLanguage:(BOOL) isMyanmar {
if (hasRun == YES) {
return;
}
hasRun = YES;
NSUserDefaults * userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setBool:isMyanmar forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
//>>>>>>>>>>>>>>>>>>>> the problem is probably here
[self startCountDown];
}
Any code that runs after changing language code fails. The problem is probably there.
Edit: the thread problem is gone but the countdown isn't happening anymore.
After I have moved the code in changeLanguage into the methods that call it, the problem is mysteriously gone. (Repetitive but it works.)
- (void)changeLanguageToEnglish {
[theLock lock];
if (hasRun == YES) {
[theLock unlock];
return;
}
hasRun = YES;
[userdefaults setBool:false forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self startCountDown];
[theLock unlock];
}
- (void)changeLanguageToMyanmar {
[theLock lock];
if (hasRun == YES) {
[theLock unlock];
return;
}
hasRun = YES;
[userdefaults setBool:true forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self startCountDown];
[theLock unlock];
}
But the problem is that the countdown isn't happening anymore.
You could use an NSTimer to perform the countdown and a static variable for the counter.
The method startCountDown starts the timer.
The method countDown:(NSTimer *)timer is called every 0.5 seconds. The passed NSTimer argument is exactly the timer which has been started.
it performs the action according to its value and decrements the counter. If the counter is 0, the timer is invalidated and the controller dismissed.
static UInt8 counter = 0;
- (void)startCountDown {
countDownFlag = [[UIImageView alloc] init];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
[self.view addSubview:countDownFlag];
counter = 3;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
- (void)countDown:(NSTimer *)timer {
if (counter == 0) {
[timer invalidate];
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
NSArray *imageNameArray = #[#"", #"One", #"Two", #"Three"];
UIImage *image = [UIImage imageNamed:imageNameArray[counter]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.countDownFlag setImage:image];
});
counter--;
}
Place static int i = 3; outside your method countDown, the way you did it it declares new variable every time you call that method.
Hello I have a problem with my timer and I don't understand where is the problem my problem is at every milesecunds or seconds my timer disappear and appear i don't understand why :
- (void)viewDidLoad {
[super viewDidLoad];
self.BtnA.transform = CGAffineTransformMakeRotation( M_PI );
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(substractTime) userInfo:nil repeats:YES];
[self reset:nil];
}
- (IBAction)touchBtnA:(id)sender {
if (enabledA) {
[self.BtnA setEnabled:NO];
[self.BtnB setEnabled:YES];
enabledA = NO;
enabledB = YES;
[self.BtnA setAlpha:0.33];
[self.BtnB setAlpha:1.0];
} else {
[self.BtnA setEnabled:YES];
[self.BtnB setEnabled:NO];
enabledA = YES;
enabledB = NO;
[self.BtnB setAlpha:0.33];
[self.BtnA setAlpha:1.0];
}
}
- (IBAction)touchBtnB:(id)sender {
if (enabledB) {
[self.BtnB setEnabled:NO];
[self.BtnA setEnabled:YES];
enabledB = NO;
enabledA = YES;
[self.BtnB setAlpha:0.33];
[self.BtnA setAlpha:1.0];
} else {
[self.BtnB setEnabled:YES];
[self.BtnA setEnabled:NO];
enabledB = YES;
enabledA = NO;
[self.BtnA setAlpha:0.33];
[self.BtnB setAlpha:1.0];
}
}
- (void)substractTime {
if (enabledA) {
_remainingTimeA--;
if (_remainingTimeA == 0)
{
[self pause:nil];
[self.BtnA setEnabled:NO];
}
[self updateTime:A];
}
if (enabledB) {
_remainingTimeB--;
if (_remainingTimeB == 0)
{
[self pause:nil];
[self.BtnB setEnabled:NO];
}
[self updateTime:B];
}
}
- (void)updateTime: (TimerType)type {
NSInteger time = type == A ? _remainingTimeA : _remainingTimeB;
NSInteger minutes = time / 600;
NSInteger seconds = (time/10) % 60;
NSInteger milliseconds = time % 10;
if (type == A)
{
[self.BtnA setTitle:[NSString stringWithFormat:#"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal];
}
else
{
[self.BtnB setTitle:[NSString stringWithFormat:#"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal];
}
}
- (IBAction)pause:(id)sender {
enabledA = enabledB = NO;
}
- (IBAction)reset:(id)sender {
enabledA = enabledB = NO;
[self.BtnA setEnabled:YES];
[self.BtnB setEnabled:YES];
_remainingTimeA = _remainingTimeB = 6000;
[self updateTime:A];
[self updateTime:B];
[self.BtnA setAlpha:1.0];
[self.BtnB setAlpha:1.0];
}
Thanks all for feature help.
You should know that NSTimer doesn't grant you absolute accuracy of repeating interval (1.1 in your case) of invoking selector. In other words, you should count difference between current and previous selector calls, that will be exact interval
Hi I am building an app in which I want my contents to be displayed on a view which is horizontally scroll-able.
I have implemented the following code for it:
-(void)DownLoadData:(NSString *)indexSelect
{
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)DownloadNext:(NSString *)indexSelect
{
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
}
}
[self loadScrollView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
_imageView1.hidden=YES;
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
// _txtView.frame=CGRectMake(4.0f,316.0f,310.0f,159.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._Writer setText:[Dic valueForKey:#"AUTHOR"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
[self loadScrollView];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[self DownLoadData:resultDic];
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(loadScrollView)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(loadScrollView)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
[self loadScrollView];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
[self loadScrollView];
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(void)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
-(void)loadScrollView
{
_scrollView.contentSize = CGSizeMake(0, _scrollView.frame.size.height);
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [_arrUrlLinks count]; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
count=1;
// a page is the width of the scroll view
_scrollView.pagingEnabled = YES;
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * [_arrUrlLinks count], _scrollView.frame.size.height);
_scrollView.showsHorizontalScrollIndicator =YES;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
pageControl.numberOfPages = [_arrUrlLinks count];
pageControl.currentPage = 0;
[_scrollView addSubview:_txtView];
[_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
[controller.view addSubview:_txtView];
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count])
return;
// replace the placeholder if necessary
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
}
else{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController_ipad" bundle:nil];
}
[controller initWithPageNumber:page];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage");
[viewControllers replaceObjectAtIndex:page withObject:controller];
// [controller release];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = _scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
// _txtView.frame=frame;
// _imageview.frame=frame;
// _txtView.frame=CGRectMake(4.0f,316.0f,310.0f,159.0f );
_txtView=#"hello";
// [controller.view addSubview:_txtView];
[_imageView1 addSubview:controller.view];
// [_txtView addSubview:controller.view];
// [scrollView addSubview:controller.view];
NSLog(#"loadscrollviewwithpage................>>>>>>>>>>>>");
// [self._header setText: [Dic valueForKey:#"header"]];
// [self DownLoadData:resultDic];
//[self SetValuesInUserInterface:Dic];
[self DownloadNext:resultDic];
}
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count]) return;
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller != [NSNull null]) {
if (nil != controller.view.superview)
[controller.view removeFromSuperview];
[viewControllers replaceObjectAtIndex:page withObject:[NSNull null]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"Unloadscrollviewwithpage");
// [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// NSLog(#"current page %d",page);
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
count=page+1;
// [self newCountTitleSet];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollViewLoc
{
CGFloat pageWidth = scrollViewLoc.frame.size.width;
CGPoint translation = [scrollViewLoc.panGestureRecognizer translationInView:scrollViewLoc.superview];
int page = floor((scrollViewLoc.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(translation.x > 0)
{
if(_strCurrentNewsSelect!=0)
{
if(page==0)
{
NSLog(#"OK");
NSLog(#"scrollviewwillbegindragging=0");
[self DownLoadDataPrevious:[_strCurrentNewsSelect.integervalue]-1];
}
}
else{
if(page==1)
{
NSLog(#"previous button");
[self btnPreviousClick];
}
}
} else
{
// [_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage else");
[self btnPreviousClick];
NSLog(#"previous news");
// if(galleryItemClick+1!=[arrGallaeryUrl count])
//
// {
//
if(page+1==[_arrUrlLinks count])
//
{
//
NSLog(#"====....>>>>>>>");
}
count=count+1;
}
}
By using this code I am able to create the view controllers according to my array count[_arrUrlLinks] but the contents are not loaded on these views. On my first view I can only see an image view in black color rest of the views are blank.
How can I get the contents loaded on these views?
I am new to App Development, sorry if I am asking silly questions :(
I am developing a Quiz App. Whenever I give a right or wrong answer, an image appears with right or wrong answer result, however it stays for a few seconds, but after that - it does not continue with the next question. It just shows my background images with buttons. How can I set a code, that it goes straight to a new question, when the result image is gone.
I will be very thankful for your help.
I just want that after the Result-image closes, the quiz continues with the next question.
This is the code i have setup in Game.m file.
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
-(void)WrongAnswer{
LivesNumber = LivesNumber - 1;
Lives.text = [NSString stringWithFormat:#"%i", LivesNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
imageQuestion.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"wrong.png"];[self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
Answer1Correct ==YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
I think the issue is that you never set Answer1Correct to anything. so if you add Answer1Correct ==YES to the correct answer method and Answer1Correct ==NO to the wrong method then it should work
-(void)Results{ // just change formate of answer.
Results.hidden = YES;
}
-(IBAction)Answer1: (id) sender{
if (Answer1Correct ==YES) {
[self RightAnswer];
}else{
[self WrongAnswer];
}
}
-(IBAction)Answer2: (id) sender{
if (Answer2Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer3: (id) sender{
if (Answer3Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
i may be wrong here but I think you need an if to the else.
But I could be wrong.
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}else{
donextcard();
}
if you want to know how to make that function we would need to see more of the code.