Just started Objective-C - trying to make 4 images fadein/fadeout continuously.
The code below is not working. I know the button is working because the text of my label changes, however no pictures animate. No errors either ...
h.
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UIImageView *viewer;
}
#property (nonatomic, retain) UIImageView *viewer;
#property (nonatomic,retain) IBOutlet UILabel *label1;
#end
m.
-(IBAction)startImageViewAnimation
{
label1.text = #"CHECK?";
NSArray *animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"backgrounds_app1-01.png"],
[UIImage imageNamed:#"backgrounds_app2-02.png"],
[UIImage imageNamed:#"backgrounds_app3-03.png"],
[UIImage imageNamed:#"backgrounds_app4-04.png"],
nil];
viewer = [[UIImageView alloc] initWithFrame:self.view.frame];
viewer.animationImages = animationImages ;
viewer.animationRepeatCount = 2;
viewer.animationDuration= 4.0;
[viewer startAnimating];
[NSTimer scheduledTimerWithTimeInterval:4.0 target:self
selector:#selector(animationDone:)
userInfo:nil repeats:NO];
}
-(void)animationDone:(NSTimer*)inTimer
{
[inTimer invalidate];
inTimer = nil;
NSLog(#"animationDone ");
}
After initialising the image view, you'll have to add it as a subview:
viewer = [[UIImageView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:viewer];
Related
I have been doing an Project for IOS which is written in Objective C. Theres a requirement where i have to put a Button or Label below a table view which kind of act as an Dialog like view over an WebView. There is already an header view embedded into the table view, its work well, but when i try to place the button or label below the table view using Storyboard its not working as expected it actually not positioning below the TableView. Below is the image how my View is laid out :
This is how it looks currently :
Below is the code for my view controller :
ViewController.h:
#import "FlatUIKit.h"
#interface NothiViewController : UIViewController
{
IBOutlet UIWebView *mainWebView;
IBOutlet UISegmentedControl *segmentControl;
IBOutlet UIView *viewNothiPermittedUsers;
IBOutlet UILabel *labelTitleNothiPermittedUsers;
IBOutlet UITableView *tableViewNothiPermittedUsers;
}
#property (nonatomic,strong) NSArray *arrNothiPermittedUsers;
#property(nonatomic,retain) ModelNothi *currentModelNothi;
- (void)updateRightBar:(BOOL)all;
#end
#interface CellNothiPermittedUserList : UITableViewCell
{
}
#property (nonatomic, strong) IBOutlet UILabel *labelUserName;
#property (nonatomic, strong) IBOutlet FUIButton *buttonSend;
#end
ViewController.m:
#interface NothiViewController ()<UIWebViewDelegate,CustomAlertViewDelegate>
{
RequestNothiActionApiType currentNothiActionApiType;
AlertType currentAlertType;
}
#property(nonatomic,strong)NSData *dataNotangsho;
#property(nonatomic,strong)NSData *dataPotrangsho;
#end
#implementation NothiViewController
#synthesize currentModelNothi;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = APP_VIEW_BACKGROUND_COLOR;
mainWebView.delegate = self;
mainWebView.backgroundColor = UIColor.clearColor;
mainWebView.opaque = YES;
mainWebView.scalesPageToFit = YES;
UIFont *font = [UIFont systemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
[segmentControl setTitleTextAttributes:attributes
forState:UIControlStateNormal];
segmentControl.tintColor = COLOR_LOGIN_BUTTON;
self.dataNotangsho = nil;
self.dataPotrangsho = nil;
currentNothiActionApiType = API_TYPE_NOTANGSHO;
NSDictionary *params = #{#"data_ref": #"api",
#"api_key": API_KEY,
#"user_designation": [AppSupporter sharedInstance].currentDesignationID};
NSString *api = [NSString stringWithFormat:#"%#/%#",API_NOTHI_NOTANGSHO,self.currentModelNothi.nothiParts];
CGRect frame = segmentControl.frame;
frame.origin.y = NAV_BAR_HEIGHT + STATUS_BAR_HEIGHT;
segmentControl.frame = frame;
segmentControl.backgroundColor = APP_VIEW_BACKGROUND_COLOR;
// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, .5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self connectServer:api withParams:params withProgressMessage:#"তথ্য লোড হচ্ছে, একটু অপেক্ষা করুন..."];
});
viewNothiPermittedUsers.hidden = YES;
viewNothiPermittedUsers.backgroundColor = [UIColor colorWithWhite:0.0F alpha:0.7f];
labelTitleNothiPermittedUsers.backgroundColor = [UIColor lightGrayColor];
[labelTitleNothiPermittedUsers.layer setCornerRadius:8.0f];
labelTitleNothiPermittedUsers.layer.masksToBounds = YES;
labelTitleNothiPermittedUsers.font = [UIFont boldFlatFontOfSize:16.0f];
tableViewNothiPermittedUsers.backgroundColor = [UIColor whiteColor];
tableViewNothiPermittedUsers.tableFooterView = [[UIView alloc] initWithFrame : CGRectZero];
[tableViewNothiPermittedUsers.layer setCornerRadius:8.0f];
tableViewNothiPermittedUsers.layer.masksToBounds = YES;
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(notifyNothiForward:) name:EventNothiForward object:nil];
}
Any help would be highly appreciated. Note i am kind of new to IOS programming and the project was written by someone else, which i just got now to extend it, so i am little aware of positioning views at the moment.
In my xcode project I have four screens and push segues between them. I found one bag when I go from mainscreen to second screen I faced with delay 2-3 seconds. After that segues to all another screen working fast.
I think probably problem is in creation
self.navigationController.viewControllers array
And when I forced push segue the first time this array was created with some delay and after when I go between screens I automatically switched between objects in this Array without delay.
So, my question: How can I forced create this viewcontrollers array when my main screen loading and working without first push segue delay?
My main viewController code:
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UILabel *bestScore;
#property (strong, nonatomic) IBOutlet UILabel *bibleVerseLabel;
#property (strong, nonatomic) IBOutlet UILabel *questionLabel;
#property (strong, nonatomic) IBOutlet UILabel *scoreLabel;
#property (strong, nonatomic) IBOutlet UIButton *startButton;
#end
#implementation ViewController
- (void)viewDidLoad {
[NSThread sleepForTimeInterval:1];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)initButtonAndLabelViews{
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg1.png"]];
_bibleVerseLabel.font = [UIFont fontWithName:#"BebasNeueBold" size:24];
_questionLabel.font = [UIFont fontWithName:#"BebasNeueBook" size:34];
_scoreLabel.font = [UIFont fontWithName:#"Bad Script" size:21];
_bestScore.font = [UIFont fontWithName:#"Bad Script" size:21];
_startButton.layer.cornerRadius = 5;
_startButton.layer.borderWidth = 0.2;
_startButton.clipsToBounds = YES;
_startButton.titleLabel.font = [UIFont fontWithName:#"BebasNeueBold" size:34];
_startButton.contentEdgeInsets = UIEdgeInsetsMake(6, 0, 0, 0);
}
-(void)viewWillAppear:(BOOL)animated{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
[self initButtonAndLabelViews];
[self.navigationController.navigationBar setTranslucent:YES];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.view.backgroundColor = [UIColor clearColor];
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
_bestScore.text = [NSString stringWithFormat:#"%ld", (long)[[NSUserDefaults standardUserDefaults] integerForKey:#"BestScore"]];
[self randomBibleVerse];
}
- (void)randomBibleVerse{
NSInteger randomVerseNumber = arc4random()%6;
switch (randomVerseNumber) {
case 0:
_bibleVerseLabel.text = #"«Слово Твое — светильник ноге моей и свет стезе моей»\n\n(Псалом 118:105)";
break;
case 1:
_bibleVerseLabel.text = #"«Ибо Ты возвеличил слово Твое превыше всякого имени Твоего»\n\n(Псалом 137:2)";
break;
case 2:
_bibleVerseLabel.text = #"«Написано:не хлебом одним будет жить человек, но всяким словом, исходящим из уст Божиих»\n\n(Матфея 4:4)";
break;
case 3:
_bibleVerseLabel.text = #"«Hо слово Господне пребывает вовек; а это есть то слово, которое вам проповедано»\n\n(1-ое Петра 1:25)";
break;
case 4:
_bibleVerseLabel.text = #"«Слова Господни – слова чистые, серебро, очищенное от земли в горниле, семь раз переплавленное»\n\n(Псалом 11:7)";
break;
case 5:
_bibleVerseLabel.text = #"«Радуюсь Я слову Твоему, как получивший великую прибыль»\n\n(Псалом 118:162)";
break;
case 6:
_bibleVerseLabel.text = #"«Закон Твой – утешение мое»\n\n(Псалом 118:77)";
break;
default:
break;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Second viewcontroller where I go with delay at firs time.
#import "CategoriesViewController.h"
#interface CategoriesViewController ()
#property (assign, nonatomic) NSInteger category1Number;
#property (assign, nonatomic) NSInteger category2Number;
#property (assign, nonatomic) NSInteger category1SelectedNumber;
#property (assign, nonatomic) NSInteger category2SelectedNumber;
#end
#implementation CategoriesViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg1.png"]];
[self buttonsInitiation];
}
- (void) buttonsInitiation{
[_category1 setTitle:#"НОВЫЙ Завет" forState:UIControlStateNormal];
[_category2 setTitle:#"ВетхиЙ Завет" forState:UIControlStateNormal];
_category1.layer.cornerRadius = 5;
_category1.layer.borderWidth = 0.2;
_category1.clipsToBounds = YES;
_category1.titleLabel.font = [UIFont fontWithName:#"BebasNeueBold" size:34];
_category1.contentEdgeInsets = UIEdgeInsetsMake(6, 0, 0, 0);
_category2.layer.cornerRadius = 5;
_category2.layer.borderWidth = 0.2;
_category2.clipsToBounds = YES;
_category2.titleLabel.font = [UIFont fontWithName:#"BebasNeueBold" size:34];
_category2.contentEdgeInsets = UIEdgeInsetsMake(6, 0, 0, 0);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Buttons
- (IBAction)button1:(id)sender{
_category1SelectedNumber = 1;
[[NSUserDefaults standardUserDefaults]setInteger:_category1SelectedNumber forKey:#"MainCategorySaved"];
}
- (IBAction)button2:(id)sender{
_category1SelectedNumber = 2;
[[NSUserDefaults standardUserDefaults]setInteger:_category1SelectedNumber forKey:#"MainCategorySaved"];
}
#end
The problem was in several buttons on second screen. When I remove them all became fine.
Low frame rate during UINavigationController push transition
I'm trying to build a timer app. When the timer hits a certain number (say 5), I want an image to appear. I have the timer working, and the image shows up, but when I declare an if statement to hide the image when the timer has not reached 5, the image shows up anyways. Furthermore, when I declare the UIImageview at the bottom, Xcode reads me the error of "Local declaration of 'images' hides instance variable.
Thank you for any help you can offer! I just started programming.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController;
-(IBAction)Start:(id)sender; {
Timer = [NSTimer scheduledTimerWithTimeInterval:1 target: self selector:#selector(TimerCount) userInfo: nil repeats:YES];
}
-(void)TimerCount{
CountNumber = CountNumber + 1;
TimerDisplay.text=[NSString stringWithFormat:#"%i", CountNumber];
if(CountNumber < 6) {
imagesx.hidden = YES;
}
if(CountNumber > 6){
imagesx.hidden = NO;
}
}
-(IBAction)UIImage:(id) sender{
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Images.jpg"]];
if (CountNumber < 6){
imagesx.hidden = YES;
}
}
-(IBAction)Stop:(id)sender{
[Timer invalidate];
TimerDisplay.text=[NSString stringWithFormat:#"%i", CountNumber];
}
-(IBAction)Reset:(id)sender{
CountNumber = 0;
[Timer invalidate];
CountNumber = 0;
TimerDisplay.text=[NSString stringWithFormat:#"%i", CountNumber];
Timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(TimerCount) userInfo:nil repeats:YES];
[Timer invalidate];
}
-(IBAction)Restart:(id)sender{
CountNumber = 0;
TimerDisplay.text = [NSString stringWithFormat:#"%i", CountNumber];
CountNumber = 0;
Timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(TimerCount) userInfo:nil repeats: YES];
if (CountNumber < 6){
imagesx.hidden = YES;
}
if (CountNumber > 6){
imagesx.hidden = NO;
}
}
- (void)viewDidLoad{
//create UIImage view programmatically
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImageView *imagesx =[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
imagesx.image=[UIImage imageNamed:#"images.jpeg"];
[self.view addSubview:imagesx];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
View Controller.h:
#import <UIKit/UIKit.h>
int CountNumber;
#interface ViewController : UIViewController
{
IBOutlet UILabel *TimerDisplay;
UIImageView *imagesx;
NSTimer *Timer;
}
-(void)TimerCount;
-(IBAction)Start:(id)sender;
-(IBAction)Stop:(id)sender;
-(IBAction)Restart:(id)sender;
#property (strong, nonatomic) IBOutlet UILabel *FirstiPhoneapp;
#property (strong, nonatomic) IBOutlet UILabel *ByJuliaTu;
#property (strong, nonatomic) IBOutlet UIButton *Start;
#property (strong, nonatomic) IBOutlet UIButton *Reset;
#property (strong, nonatomic) IBOutlet UIButton *Terminate;
#property (strong, nonatomic) IBOutlet UIButton *Restart;
#end
You declared your image view as an instance variable with the name "imagesx"
#interface ViewController : UIViewController
{
IBOutlet UILabel *TimerDisplay;
UIImageView *imagesx; <-----your ivar
NSTimer *Timer;
}
So now your view controller has a spot in memory to place an image view.
when viewDidLoad: is called you are doing this:
UIImageView *imagesx =[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
This variable (pointer to a UIImageView) has the same name is the instance variable. This will hide access to that ivar and create a new spot in memory for this local version. In other words when you do this in viewDidLoad:
- (void)viewDidLoad{
//create UIImage view programmatically
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// You are declaring a new image view here with the same name so it "overrides" or hides the ivar by creating a new local one:
UIImageView *imagesx =[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
// You are assigning your newly created image view to this local variable
imagesx.image=[UIImage imageNamed:#"Matthijs"];
// adding it to the view, which works but:
[self.view addSubview:imagesx];
// the method returns, this local variable is gone and the ivar is still nil
}
// The ivar is never getting a pointer to your newly created image view. You can't access it after the method returns.
if you put a breakpoint in the timerCount method
Your image view was never set to the ivar (it is nil) so you can't get to it in order to set it to hidden.
The fix is simple. Don't redeclare a new image view in viewDidLoad:, just assign it to your ivar:
imagesx = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200,200)];
Or if you do, declare a new one and change the name:
UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50.0f, 50.0f, 200.0f, 200.0f)];
then assign that to your ivar
imagesx = imageView;
Your code is very hard to follow. You shouldn't create ivars anymore, you can just create a proper for the NSTimer and the UIImageView. Also I'm not sure why you created outlets to the buttons if you're just using the IBActions.
In your viewDidLoad you are redeclaring imagesx and adding it as a subview so when you use the ivar in the timer call, you're actually looking at a nil pointer.
You should declare your NSTimer and the UImageView as properties:
#property (strong, nonatomic) NSTimer * timer;
#property (weak, nonatomic) IBOutlet UIImageView * imageView; // Connect this to an ImageView in the storyboard instead of creating it in code
In your .m file you should access the timer and the image as properties:
self.timer =
self.imageView.image = [UIImage imageNamed:#"..."];
I've been experiencing some difficulties with particle effects. Originally I posted a question about how the particle effects in my app were different when on an ios6 device.
Particle system looks different on iOS 6 and ios7
I Originally designed the app on an ios7 device and got the particles looking like I wanted, but on the ios6 device the particles were smaller and displaced.
I was told it was problem between ios6 and ios7 and that changing the media timing could fix it.
Ive tried everything, but nothing has worked.
Eventually I tried just creating a separate app and pasted in the code from this tutorial - http://weblog.invasivecode.com/post/45058779586/caemitterlayer-and-the-ios-particle-system-lets in the view did load. The particles work as they should, but when I put the same code into my current apps viewDidLoad. The particles were all over the place and not doing what they should be.
I'm wandering if there is something in my current app that Im missing, that is upsetting the particles. Can anyone suggest things to look for?
Originally the particle effects were subclassed and being called after adding a subview to my main view.
Here is my view controller .h code (I've taken out some irrelevant control object properties and outlets)
#interface HHViewController : UIViewController < HHScoreViewdelegate>
{
IBOutlet UIButton* btnStart;
IBOutlet UIButton* btnStop;
IBOutlet UIButton* btnMore;
IBOutlet UIButton* btnHelp;
IBOutlet UIButton* btnTessilaCoil;
IBOutlet UIImageView* imgAnimatedTessila;
IBOutlet UIImageView* imgBubble;
IBOutlet UIImageView* imgSteam;
IBOutlet UIImageView* imgMachineLightsTop;
IBOutlet UIImageView* imgBackground;
NSTimer* StopSignTimer;
NSTimer* timer;
NSTimer* lightMachineTimer;
NSTimer* ComputerLightsTimer;
CGFloat AnimationDelay;
AVAudioPlayer* audioPlayer;
AVAudioPlayer* audioPlayer2; //Used for game end audio, so that it doesnt interupt last letter/number audio
int pageValue;
IBOutlet UIButton* btnSetting;
IBOutlet UIButton* btnIAP;
IBOutlet UIButton* btnNext;
IBOutlet UIButton* btnForward;
IBOutlet UIImageView* imgLightMachine;
IBOutlet UIImageView* imgComputerLights;
NSString* strletterName;
HHScoreView * scoreSelection;
More * MorePanelView;
InAppPurchase * InAppPurchaseView;
NSMutableArray* ButtonBackgroundImages;
NSMutableArray* AlphabetBubbles;
NSMutableArray* SavedBubblePositions;
NSTimer* bubbleBlinkingTimer;
int wrongbubbleTapCount;
IBOutlet UIImageView* imgAlphabetDisplay;
IBOutlet UILabel* lblNextOneToPop;
// Code from Particle Tutorial
CAEmitterLayer *_myEmitter;
CAEmitterCell *_myCell;
// End code form Particle Tutorial
}
// Code from Particle Tutorial
#property(nonatomic, retain) CAEmitterLayer *_myEmitter;
#property(nonatomic, retain) CAEmitterCell *_myCell;
// End code form Particle Tutorial
#property(nonatomic,strong) UILabel* lblNextOneToPop;
#property(nonatomic,strong) NSTimer* SteamTimer;
#property(nonatomic,strong) NSTimer* StopSignTimer;
#property(nonatomic,strong) NSTimer* timer;
#property(nonatomic,strong) NSTimer* lightMachineTimer;
#property(nonatomic,strong) NSTimer* ComputerLightsTimer;
#property(nonatomic,retain)IBOutlet UIButton* btnStart;
#property(nonatomic,retain)IBOutlet UIButton* btnStop;
#property(nonatomic,retain)IBOutlet UIButton* btnMore;
#property(nonatomic,retain)IBOutlet UIButton* btnHelp;
#property(nonatomic,retain)IBOutlet UIButton* btnSetting;
#property(nonatomic,retain)IBOutlet UIButton* btnTessilaCoil;
#property(nonatomic,retain)IBOutlet UIImageView* imgAnimatedTessila;
#property(nonatomic,retain)IBOutlet UIImageView* imgSteam;
#property(nonatomic,retain)IBOutlet UIImageView* imgMachineLightsTop;
#property(nonatomic,retain)IBOutlet UIImageView* imgBackground;
#property(nonatomic,retain)IBOutlet UIScrollView* scScrollView;
#property(nonatomic,retain)IBOutlet IBOutlet UIButton* btnNext;
#property(nonatomic,retain)IBOutlet IBOutlet UIButton* btnForward;
#property(nonatomic,retain)IBOutlet UIImageView* imgLightMachine;
#property(nonatomic,retain)IBOutlet UIImageView* imgComputerLights;
#property(nonatomic,retain)NSString* strletterName;
#property(assign)int allLettersEventCount;
#property(nonatomic,retain) NSArray* ButtonBackgroundImages;
#property Boolean StopButtonClicked;
#property Boolean BubbleAOnscreen;
#property (nonatomic,assign) BOOL cancelAll;
#property int pageValue;
#property int positionRotation;
-(IBAction)tapPiece:(UITapGestureRecognizer *)recognizer;
-(IBAction)actionStartSign:(id)sender;
-(IBAction)actionStopSign:(id)sender;
-(IBAction)actionMoreSign:(id)sender;
-(IBAction)actionHelpSign:(id)sender;
-(IBAction)actionTessilaCoil:(id)sender;
-(IBAction)actionbtnHelp:(id)sender;
-(IBAction)actionbtnSetting:(id)sender;
-(IBAction)actionbtnIAP:(id)sender;
+(HHViewController*)sharedManager;
- (IBAction)purchaseItem:(id)sender;
#property (strong, nonatomic) InAppPurchase *purchaseController;
#end
Here is the code from my viewcontroller .m where I added the code from the tutorial.
#interface HHViewController ()
{
}
#end
#implementation HHViewController
static int OrderingSequence = 0;
#synthesize _myEmitter, _myCell;
/*
TeslarGlowEffect* ShowGlow;
SteamEffect* ShowSteam;
BubbleBurst* PopBubble;
*/
//TeslarTimerSparks* TeslarTimer;
- (void)viewDidLoad
{
[super viewDidLoad];
CFTimeInterval currentTime = [self.view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
NSLog(#"Current media Timing = %f", currentTime);
// Code from tutorial
CAEmitterLayer *emitterLayer = [CAEmitterLayer layer]; // 1
emitterLayer.emitterPosition = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.origin.y); // 2
emitterLayer.emitterZPosition = 10; // 3
emitterLayer.emitterSize = CGSizeMake(self.view.bounds.size.width, 0); // 4
emitterLayer.emitterShape = kCAEmitterLayerSphere; // 5
CAEmitterCell *emitterCell = [CAEmitterCell emitterCell]; // 6
emitterCell.scale = 0.1; // 7
emitterCell.scaleRange = 0.2; // 8
emitterCell.emissionRange = (CGFloat)M_PI_2; // 9
emitterCell.lifetime = 5.0; // 10
emitterCell.birthRate = 10; // 11
emitterCell.velocity = 200; // 12
emitterCell.velocityRange = 50; // 13
emitterCell.yAcceleration = 250; // 14
emitterCell.contents = (id)[[UIImage imageNamed:#"Steam1.png"] CGImage]; // 15
emitterLayer.emitterCells = [NSArray arrayWithObject:emitterCell]; // 16
[self.view.layer addSublayer:emitterLayer]; // 17
//end code from tutorial
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appWillEnterForegroundNotification:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appWillEnterBackgroundNotification:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[btnStart addTarget:self action:#selector(actionStartSign:) forControlEvents:UIControlEventTouchUpInside];
//NSLog(#"OrderingSequence = %d",OrderingSequence );
imgAnimatedTessila.image = [UIImage imageNamed:KTESSILAIMAGE];
self.alphebetindex = 0;
wrongbubbleTapCount = 0;
//// Load a bunch of arrays used in the game.
[btnHelp addTarget:self action:#selector(actionbtnHelp:) forControlEvents:UIControlEventTouchUpInside];
[btnSetting addTarget:self action:#selector(actionbtnSetting:) forControlEvents:UIControlEventTouchUpInside];
NSString* strFirstTimeloaded = [[NSUserDefaults standardUserDefaults]valueForKey:#"FirstTime"];
if(strFirstTimeloaded == nil)
{
// Show preference page if first time used.
[[NSUserDefaults standardUserDefaults]setValue:#"English" forKey:#"Language"];
LanguagesSelectView* selection = [[LanguagesSelectView alloc]initWithFrame:CGRectMake(0, 0, 1024, 748)];
[self.view addSubview:selection];
[[NSUserDefaults standardUserDefaults]setValue:#"FirstTime" forKey:#"FirstTime"];
}
positionRotation = 0;
self.strletterName = #"29";
self.allLettersEventCount = 0;
[[NSUserDefaults standardUserDefaults] setValue:#"One" forKey:#"Mode"];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(enableSetting) name:#"EnableSetting" object:nil];
//[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(LetterTapped:) name:#"LetterTapped" object:nil];
btnStop.hidden = YES;
btnNext.hidden = YES;
btnForward.hidden = YES;
[self addGestureRecognizersToView];
//Create timer for release of steam from bubble machine
SteamTimer = [NSTimer scheduledTimerWithTimeInterval:5.2 target:self selector:#selector(ShowSteamEffect) userInfo:nil repeats:YES];
//Set Font for lblNextOneToPop
[lblNextOneToPop setFont:[UIFont fontWithName:#"SF Slapstick Comic" size:110]];
lblNextOneToPop.hidden = YES;
}
Here is one of my particle effects that was working on my ios7 iPad, but on the ios6 iPad, the effect looked totally different.
It was after long hrs trying to figure out why the ios7 and ios6 looked different that I tried the exercise of putting the tutorial code into a new app and then it into my own app. In my app the particles are totally different, but as they should be in the new app.
With respect to #matt's comments below. I know there must be something going on with my app, but I can't see it. I've looked all over the web and all through my code and I think I'm missing something.
All I want are three particles effects that appear at specific locations regardless of iOS version. One of them on user touch. The effect below is just one of them. I've tried the CAmediaTiming thing, but that didn't work.
SteamEffect.h
#import <UIKit/UIKit.h>
#interface SteamEffect : UIView
#end
The steamEffect.m looks like this.
#import "SteamEffect.h"
#implementation SteamEffect
{
CAEmitterLayer* SteamEmitter;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
SteamEmitter = (CAEmitterLayer*) self.layer;
//SteamEmitter.emitterPosition= CGPointMake(0, 0);
//SteamEmitter.emitterSize = CGSizeMake(10,10);
CAEmitterCell* Steam = [CAEmitterCell emitterCell];
Steam.birthRate = 50.0f;
Steam.spin = .6f;
Steam.lifetime = 1.7f;
Steam.alphaRange = 0.2f;
Steam.alphaSpeed = 0.2f;
Steam.contents = (id)[[UIImage imageNamed:#"Steam1.png"]CGImage];
Steam.velocity = 30;
Steam.velocityRange = 50.0f;
Steam.emissionLongitude = -60.0f;
Steam.emissionRange = M_1_PI;
Steam.scale = .2f;
Steam.scaleSpeed = .5f;
Steam.yAcceleration = -200.0f;
//SteamEmitter.renderMode = kCAEmitterLayerBackToFront;//kCAEmitterLayerAdditive;
//SteamEmitter.emitterShape = kCAEmitterLayerCircle;
SteamEmitter.emitterCells = #[Steam];
SteamEmitter.emitterPosition = CGPointMake(815, 445);
//Check System Version
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:#"."];
if ([[vComp objectAtIndex:0] intValue] == 7) {
// iOS-6 code
SteamEmitter.beginTime = CACurrentMediaTime();
}
}
return self;
}
-(void)didMoveToSuperview
{
//1
[super didMoveToSuperview];
if (self.superview==nil) return;
[self performSelector:#selector(disableEmitterCell) withObject:nil afterDelay:0.5];
}
-(void)disableEmitterCell
{
[SteamEmitter setValue:#0 forKeyPath:#"birthRate"];
}
+ (Class) layerClass
{
//tell UIView to use the CAEmitterLayer root class
return [CAEmitterLayer class];
}
- (void) setEmitterPosition:(CGPoint)pos
{
SteamEmitter.emitterPosition = pos;
}
- (void) toggleOn:(bool)on
{
//SteamEmitter.birthRate = on? 300 : 0;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
I called the above from my viewcontroller .m using the following. There is also a timer in the viewDidLoad above that calls this every 5 sec. Although that is probably not the way to do it. Probably better to add the view and start it emitting every 5 sec rather than adding a new view each time, but thats a different issue.
- (void)ShowSteamEffect
{
//Check System Version because NSAttributedString only works in ios6 and above.
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:#"."];
//Create view for Steam particle effect.
//CGRect SteamFrame = CGRectMake(790, 380, 100, 100); //ORIGINAL
CGRect SteamFrame = CGRectMake(0, 0, 0, 0); //(815, 455, 100, 100)
//Show Steam effect
ShowSteam = [[SteamEffect alloc]initWithFrame:SteamFrame];
ShowSteam.hidden = NO;
[self.view insertSubview:ShowSteam aboveSubview:imgComputerLights];
}
I've got this code trying to run a simple set of images in a cycle. All I have in the app is one UIImageView declared in my View Controller's .h file:
#property (strong, nonatomic) IBOutlet UIImageView *imageDisplay;
And the following in my .m file's viewDidLoad method:
NSMutableArray *imageView = [[NSMutableArray alloc] init];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim1.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim2.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim3.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim4.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim5.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim6.png"]]];
[imageView addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"EyeAnim7.png"]]];
imageDisplay.animationImages = imageView;
imageDisplay.animationDuration = 0.25;
imageDisplay.animationRepeatCount = 50;
[imageDisplay startAnimating];
The code seems to be crashing on the "imageDisplay.animationImages" line, as if I create the UIImageView, create its getter and setter, and build, it's fine until I uncomment that line. If I do uncomment it, it keeps giving me the error until I delete the UIImageView and create a new one.
Not too sure what's happening, any help appreciated!
I am very new to objective-c and I have been getting this error also, but for a different reason. I just wanted to post my solution for anyone else who may be struggling.
So basically I have a custom class called ImagesDetailViewController which inherits from UIViewController and has an image property.
#interface ImagesDetailViewController : UIViewController
#property (strong, nonatomic) UIImage *image;
#end
I then connected my class to my UIImageView on my storyboard like so
#interface ImagesDetailViewController ()
#property (nonatomic, weak) IBOutlet UIImageView *imageView;
#end
In my viewDidLoad method I was trying to set the image for my image view like this and getting the error mentioned above (my image variable gets initialised in a prepareForSegue method)
- (void)viewDidLoad
{
[super viewDidLoad];
[self.imageView setImage:self.image];
}
So I was stumped as I bet you are all too. The problem had to do with the storyboard. Clicking on my UIImageView and then navigating to the Connections Inspector, I had somehow created 2 referencing outlets (oops...) and one was pointing to a variable called image. So when the program was running [self.imageView setImage:self.image] self.image was actually an instance of UIImageView instead of UIImage.
animationImages array MUST contain only UIImage objects. Your array contains UIImageView objects.
Also your code is unsafe - if one of the resources will not exist app will crash (trying to add nil object to the mutable array). This will be much safer:
#define kNumberOfImages 7
NSMutableArray *imageView = [[NSMutableArray alloc] init];
for(NSUInteger i = 1; i <= kNumberOfImages; i++) {
UIImage *anImage = [UIImage imageNamed:[NSString stringWithFormat:#"EyeAnim%d", i]];
if(anImage) {
[imageView addObject:anImage];
}
}
self.imageDisplay.animationImages = imageView;
self.imageDisplay.animationDuration = 0.25;
self.imageDisplay.animationRepeatCount = 50;
[self.imageDisplay startAnimating];