LandScape/Portrait size differ iOS - iphone

I have five UIButton and I need to set the frame of the UIButton in such a way that it should be for the Landscape and portrait different size.
but the from the Below code viewDidLoad its loading fine but problem is that After loading the stack When I move to the Landscape to portrait or the portrait to Landscape it should be change according to the viewdidload size which i have set ..but this is not happening...its been overlapping as previous Button is already created....what changes do i require so that when change the view ..button should come properly ..should not be overlap.
-(void)viewDidLoad{
int Height = 200;
int Yposition = 20;
for (int k=0; k<5; k++)
{
if ([UIApplication sharedApplication].statusBarOrientation== UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight) {
UIButton *loPlayButton=[UIButton buttonWithType:UIButtonTypeCustom];
[loPlayButton addTarget:self action:#selector(PlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
// loPlayButton.tag = 100+k;
NSLog(#"tag is %i",loPlayButton.tag);
loPlayButton.alpha = 1.0;
UIImage *image=[UIImage imageNamed:#"vid.png"];
[loPlayButton setBackgroundImage:image forState:UIControlStateNormal];
loPlayButton.frame=CGRectMake(520, Yposition +(k*Height +170), image.size.width, 30);
// loPlayButton.tag=3;
[mScrollView_por addSubview:loPlayButton];
[mPlayButtonsArray addObject:loPlayButton];
}
if ([UIDevice currentDevice].orientation==UIInterfaceOrientationPortrait || [UIDevice currentDevice].orientation == UIInterfaceOrientationPortraitUpsideDown) {
UIButton *loPlayButton=[UIButton buttonWithType:UIButtonTypeCustom];
[loPlayButton addTarget:self action:#selector(PlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
// loPlayButton.tag = 100+k;
NSLog(#"tag is %i",loPlayButton.tag);
loPlayButton.alpha = 1.0;
UIImage *image=[UIImage imageNamed:#"vid.png"];
[loPlayButton setBackgroundImage:image forState:UIControlStateNormal];
loPlayButton.frame=CGRectMake(440, Yposition +(k*Height +170), image.size.width, 30);
// loPlayButton.tag=3;
[mScrollView_por addSubview:loPlayButton];
[mPlayButtonsArray addObject:loPlayButton];
}}}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[self viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if(UIInterfaceOrientationIsPortrait(statusBarOrientation))
{
[self ArrangeControllsFor_Protrate];
}
else
{
[self ArrangeControllsFor_LandScape];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
switch (interfaceOrientation) {
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
//[self ArrangeControllsFor_Protrate];
[self performSelector:#selector(ArrangeControllsFor_Protrate) withObject:Nil afterDelay:0.005f];
return YES;
break;
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
[self performSelector:#selector(ArrangeControllsFor_LandScape) withObject:Nil afterDelay:0.005f];
return YES;
break;
}
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
//switch ([UIApplication sharedApplication].statusBarOrientation) {
switch (toInterfaceOrientation) {
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
//[self ArrangeControllsFor_Protrate];
[self performSelector:#selector(ArrangeControllsFor_Protrate) withObject:Nil afterDelay:0.005f];
break;
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
[self performSelector:#selector(ArrangeControllsFor_LandScape) withObject:Nil afterDelay:0.005f];
break;
}
}
-(NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
-(BOOL)shouldAutorotate
{
return YES;
}
-(void)ArrangeControllsFor_Protrate
{set frames here.
}
-(void)ArrangeControllsFor_LandScape
{set frames here.
}

Mate add the your rotation code in separate method and call it from viewDidLoad and when it changes the orientation. Like in the below code :
-(void)viewDidLoad{
[self rotateTheView];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[self rotateTheView];
}
- (void) rotateTheView{
int Height = 200;
int Yposition = 20;
for (int k=0; k<5; k++)
{
if ([UIApplication sharedApplication].statusBarOrientation== UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight) {
UIButton *loPlayButton=[UIButton buttonWithType:UIButtonTypeCustom];
[loPlayButton addTarget:self action:#selector(PlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
// loPlayButton.tag = 100+k;
NSLog(#"tag is %i",loPlayButton.tag);
loPlayButton.alpha = 1.0;
UIImage *image=[UIImage imageNamed:#"vid.png"];
[loPlayButton setBackgroundImage:image forState:UIControlStateNormal];
loPlayButton.frame=CGRectMake(520, Yposition +(k*Height +170), image.size.width, 30);
// loPlayButton.tag=3;
[mScrollView_por addSubview:loPlayButton];
[mPlayButtonsArray addObject:loPlayButton];
}
if ([UIDevice currentDevice].orientation==UIInterfaceOrientationPortrait || [UIDevice currentDevice].orientation == UIInterfaceOrientationPortraitUpsideDown) {
UIButton *loPlayButton=[UIButton buttonWithType:UIButtonTypeCustom];
[loPlayButton addTarget:self action:#selector(PlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
// loPlayButton.tag = 100+k;
NSLog(#"tag is %i",loPlayButton.tag);
loPlayButton.alpha = 1.0;
UIImage *image=[UIImage imageNamed:#"vid.png"];
[loPlayButton setBackgroundImage:image forState:UIControlStateNormal];
loPlayButton.frame=CGRectMake(440, Yposition +(k*Height +170), image.size.width, 30);
// loPlayButton.tag=3;
[mScrollView_por addSubview:loPlayButton];
[mPlayButtonsArray addObject:loPlayButton];
}
}
}

You are not supposed to call viewDidLoad manually. Do not do that.
-(void)viewWillAppear:(BOOL)animated
{
[self resetFrame:[[UIApplication sharedApplication]statusBarOrientation]];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self resetFrame:toInterfaceOrientation];
}
- (void) resetFrame: (UIInterfaceOrientation)orientation
{
if (UIInterfaceOrientationIsPortrait(orientation))
{
// For portrait
}
else
{
// for landscape
}
}

First you need remove all UIButton before adding the new 5 UIButton from your scroll.
for (UIView *button in mScrollView_por.subviews) {
if([button isKindOfClass:[UIButton class]]) {
[button removeFromSuperview];
}
}

Related

Using of NStimer to set image animation with default image

How to integrate two images where one act as default and another as animating image when app launches..The animating image should not come again even that view loads again..it should come only when app launches like default.png image..The idea is to get two default images..How can i do that?..
Here is my code...
#interface ViewController ()<UIActionSheetDelegate>
#property (nonatomic, assign) BOOL useButtons;
#end
#implementation ViewController
#synthesize carousel,Chaintop;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
carousel.type = iCarouselTypeInvertedWheel ;
CGRect ChaintopFrame = Chaintop.frame;
ChaintopFrame.origin.y = self.view.bounds.size.height;
[UIView animateWithDuration:3
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
Chaintop.frame = ChaintopFrame;
//Chainbottom.frame = ChainbottomFrame;
}
completion:^(BOOL finished){
NSLog(#"Done!");
}];
[self.view addSubview: Chaintop];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return NUMBER_OF_ITEMS;
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
UIImage *buttonImage=[NSArray arrayWithObjects:[UIImage imageNamed:#"Cover_0.png"],
[UIImage imageNamed:#"Cover_1.png"],
[UIImage imageNamed:#"Cover_2.png"],
[UIImage imageNamed:#"Cover_3.png"],
[UIImage imageNamed:#"Cover_4.png"],
[UIImage imageNamed:#"Cover_5.png"],
[UIImage imageNamed:#"Cover_6.png"],
[UIImage imageNamed:#"Cover_7.png"],nil];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 200.0f, 200.0f);
[button setImage:(UIImage*)[buttonImage objectAtIndex:index] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
-(void)dealloc{
[Chaintop release];
}
- (BOOL)carousel:(iCarousel *)_carousel shouldSelectItemAtIndex:(NSInteger)index
{
if (index == carousel.currentItemIndex)
{
NSLog(#"Should select current item");
}
else
{
NSLog(#"Should select item number %i", index);
}
return YES;
}
- (void)carousel:(iCarousel *)_carousel didSelectItemAtIndex:(NSInteger)index
{
if (index == carousel.currentItemIndex)
{
//note, this will only ever happen if useButtons == NO
//otherwise the button intercepts the tap event
NSLog(#"Did select current item");
}
else
{
NSLog(#"Did select item number %i", index);
}
}
#end
In your APP DELEGATE.
Something like this should do the job:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:self.window.bounds] autorelease];
UIImage *image = [UIImage imageNamed:#"NAMEOFYOURSPLASHSCREEN.png"];
imageView.image = image;
[self.window addSubview:imageView];
[self.window makeKeyAndVisible];
[self performSelector:#selector(remove1stSplash:) withObject:imageView afterDelay:5];
return YES;
}
- (void)remove1stSplash:(UIImageView *)1stView {
UIImageView *imageView = ...
[self.window addSubview:imageView];
[self performSelector:#selector(remove2ndSplash:) withObject:imageView afterDelay:5];
[1stView removeFromSuperView];
}
- (void)remove2ndSplash:(UIImageView *)2ndView {
[self.window addSubview:.....
[2ndView removeFromSuperView];
}
EDIT:
Link for a sample project:
Two Splash Screen display in iphone

UIView subclass won't update

I have a custom uiview that i am trying to update the frame size. I do it like this in a method once it is clicked. The method is called, and the frame value changes, however on the screen nothing happens! What I think is happening is the subclass is not being redrawn or updated
- (void)resizeWithTag:(int)tag wasTouched:(BOOL)touched
{
if (!touched) {
GameBox *box = (GameBox *)[self.view viewWithTag:40];
CGRect frame = box.frame;
frame.origin.x += 30;
box.frame = frame;
[[self.view viewWithTag:40] setFrame:CGRectMake(20, 20, 100, 73)];
[box layoutSubviews];
NSLog(#"%f", box.frame.origin.x);
markButton.enabled = NO;
guessButton.enabled = NO;
[self.view reloadInputViews];
NSLog(#"The action bar should now be hidden");
}
else if (touched) {
guessButton.enabled = YES;
markButton.enabled = YES;
[self.view reloadInputViews];
NSLog(#"The action bar should now be visible");
}
}

How to add a done button to the keyboard in landscape mode?

I have an application in which I have a text field. When I click on that the screen scrolls and the keyboard is shown. I use this code:
- (void) viewWillAppear:(BOOL)animated {
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
[self willAnimateRotationToInterfaceOrientation:orientation duration:0];
[super viewWillAppear:animated];
NSLog(#"Registering for keyboard events");
// Register for the events
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector (keyboardDidShow:) name: UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil];
// Setup content size
scrollView.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH,SCROLLVIEW_CONTENT_HEIGHT);
//Initially the keyboard is hidden
keyboardVisible = NO;
}
- (void)keyboardWillShow:(NSNotification *)note {
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for (keyboard in tempWindow.subviews) {
if([[keyboard description] hasPrefix:#"<UIKeyboard"] == YES)
if (numberPadShowing) {
[self addButtonToKeyboard];
return;
break;
} else {
for (UIView *v in [keyboard subviews]){
if ([v tag]==123)
[v removeFromSuperview];
}
}
}
}
-(void) keyboardDidShow: (NSNotification *)notif {
NSLog(#"Keyboard is visible");
// If keyboard is visible, return
if (keyboardVisible)
{
NSLog(#"Keyboard is already visible. Ignore notification.");
return;
}
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[self addButtonToKeyboard];
}
// Get the size of the keyboard.
NSDictionary* info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Save the current location so we can restore
// when keyboard is dismissed
offset = scrollView.contentOffset;
// Resize the scroll view to make room for the keyboard
CGRect viewFrame = scrollView.frame;
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;
UIInterfaceOrientation toInterfaceOrientation = [[UIDevice currentDevice] orientation];
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight )
{
CGRect textFieldRect = [myActiveTextField frame];
textFieldRect.origin.y += 20;
[scrollView scrollRectToVisible:textFieldRect animated:YES];
} else {
CGRect textFieldRect = [myActiveTextField frame];
textFieldRect.origin.y += 80;
[scrollView scrollRectToVisible:textFieldRect animated:YES];
}
NSLog(#"ao fim");
// Keyboard is now visible
keyboardVisible = YES;
}
-(void) keyboardDidHide: (NSNotification *)notif {
// Is the keyboard already shown
if (!keyboardVisible) {
NSLog(#"Keyboard is already hidden. Ignore notification.");
return;
}
// Reset the frame scroll view to its original value
scrollView.frame = CGRectMake(0, 44, SCROLLVIEW_CONTENT_WIDTH, SCROLLVIEW_CONTENT_HEIGHT);
// Reset the scrollview to previous location
scrollView.contentOffset = offset;
// Keyboard is no longer visible
keyboardVisible = NO;
}
- (void)addButtonToKeyboard {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIInterfaceOrientation toInterfaceOrientation = [[UIDevice currentDevice] orientation];
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight )
{
doneButton.frame = CGRectMake(0, 260, 160, 40);
} else {
doneButton.frame = CGRectMake(0, 163, 106, 53);
}
doneButton.adjustsImageWhenHighlighted = NO;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
[doneButton setImage:[UIImage imageNamed:#"DoneUp3.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown3.png"] forState:UIControlStateHighlighted];
} else {
[doneButton setImage:[UIImage imageNamed:#"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown.png"] forState:UIControlStateHighlighted];
}
[doneButton addTarget:self action:#selector(doneButton) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES)
[keyboard addSubview:doneButton];
} else {
if([[keyboard description] hasPrefix:#"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
}
Now the problem is that it works fine in portrait mode, but in landscape mode when I click on the textfield the keyboard will appear and the view will scroll so much that the text field being edited is no longer visible on the screen. Also on a number keyboard ( like the one found in Phone.app ) there is no custom add button in landscape mode, but there is one in portrait mode.
How do I fix this?
I use this code for add done button in landscape mode
- (void)addButtonToKeyboard {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIInterfaceOrientation toInterfaceOrientation = [[UIDevice currentDevice] orientation];
if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight )
{
doneButton.frame = CGRectMake(0, 123, 160, 39);
}
else{
doneButton.frame = CGRectMake(0, 163, 106, 53);
}
doneButton.adjustsImageWhenHighlighted = NO;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
[doneButton setImage:[UIImage imageNamed:#"DoneUp3.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown3.png"] forState:UIControlStateHighlighted];
} else {
[doneButton setImage:[UIImage imageNamed:#"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown.png"] forState:UIControlStateHighlighted];
}
[doneButton addTarget:self action:#selector(doneButton) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES)
[keyboard addSubview:doneButton];
} else {
if([[keyboard description] hasPrefix:#"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
}
this method is for both mode for number pad.

Why does the AVAudioPlayer stop method not work when switching views

I have an iphone app that displays images and plays audio selected from a main menu.
The user clicks on a button to select the image/audio combo they want. The code to switch the views with animation works fine.
All of the code to display the image, play, pause, scrub, and stop the audio while in the new view works fine too.
However, when the users clicks the Main Menu button I want the playing audio to stop. I am using viewWillDisappear:(BOOL)animated to call the stop method:
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];}
This code doesn't stop the sound when the user switches back to the main menu view. Is there a better way to do this? Am I doing something wrong?
Here is the code from the entire class where the snippet above resides:
#import "twelthPoem.h"
UIImageView *largeImageView;
#implementation twelthPoem
-(void)resetControls
{
audioPlayer.currentTime = 0;
scrubber.value = 0;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"]
forState:UIControlStateNormal];
}
-(void)play:(id)sender {
if (! audioPlayer.playing) {
audioPlayer.play;
[playButton setImage:[UIImage imageNamed:#"pauseHL.png"] forState:UIControlStateNormal];
}
else {
audioPlayer.pause;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
}
[self becomeFirstResponder];
}
-(void)stop:(id)sender {
audioPlayer.stop;
[self resetControls];
}
-(void)changeVolume:(id)sender {
audioPlayer.volume = volume.value;
[self becomeFirstResponder];
}
-(void)scrub:(id)sender {
if (audioPlayer.playing) {
audioPlayer.pause;
audioPlayer.currentTime = scrubber.value;
audioPlayer.play;
}
else
audioPlayer.currentTime = scrubber.value;
[self becomeFirstResponder];
}
-(void)createControls {
//play/pause button
playButton = [UIButton buttonWithType:UIButtonTypeCustom];
[playButton setFrame:CGRectMake(60,405,80,20)];
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:#selector(play:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
//stop button
stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[stopButton setFrame:CGRectMake(180,405,80,20)];
[stopButton setImage:[UIImage imageNamed:#"stopHL.png"] forState:UIControlStateNormal];
[stopButton addTarget:self action:#selector(stop:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stopButton];
//volume control
volume = [[UISlider alloc] initWithFrame:CGRectMake(10,445,145,20)];
[volume addTarget:self action:#selector(changeVolume:)
forControlEvents:UIControlEventValueChanged];
volume.minimumValue = 0.0;
volume.maximumValue = 1.0;
volume.value = audioPlayer.volume;
volume.continuous = YES;
[self.view addSubview:volume];
//scrubber control
scrubber = [[UISlider alloc] initWithFrame:CGRectMake(165,445,145,20)];
[scrubber addTarget:self action:#selector(scrub:)
forControlEvents:UIControlEventValueChanged];
scrubber.minimumValue = 0.0;
scrubber.maximumValue = audioPlayer.duration;
scrubber.value = audioPlayer.currentTime;
scrubber.continuous = NO;
[self.view addSubview:scrubber];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype)
{
case UIEventSubtypeRemoteControlTogglePlayPause:
[self play:nil];
break;
case UIEventSubtypeRemoteControlNextTrack:
//do nothing
break;
case UIEventSubtypeRemoteControlPreviousTrack:
//do nothing
break;
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidLoad {
//for scrolling the image
[super viewDidLoad];
CGRect scrollFrame = CGRectMake(0,40,320,350);
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
scrollView.minimumZoomScale = 1.0;
scrollView.maximumZoomScale = 1.5;
scrollView.delegate = self;
UIImage *bigImage = [UIImage imageNamed:#"birches.png"];
largeImageView = [[UIImageView alloc] initWithImage:bigImage];
[scrollView addSubview:largeImageView];
scrollView.contentSize = largeImageView.frame.size; //important!
[self.view addSubview:scrollView];
[scrollView release];
//for playing the recording
NSString *filePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"birches_final_mp3.mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *error = nil;
OSStatus status = AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
status = AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory);
AudioSessionSetActive(YES);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
if (error )
NSLog(#"An error occurred: %#",error);
else
{
audioPlayer.volume = 0.3;
[audioPlayer prepareToPlay];
[self createControls];
}
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return largeImageView;
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
interrupted = audioPlayer.playing;
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
if (interrupted)
audioPlayer.play;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
[self resetControls];
}
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];
}
- (void)dealloc {
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[scrubber release];
[volume release];
[audioPlayer release];
[super dealloc];
}
#end
You call methods in objective-c using the following syntax.
[audioPlayer stop];
audioPlayer.stop will not work.
Same goes for other places as well.
audioPlayer.stop will not work mostly because it needs an expression after it, e.g. audioPlayer.stop = //expression, stop is a bool, so you can say audioPlayer.stop = YES; or [audioPlayer stop];

Passing URL into method

Hi i have a question here,
i'm able to get the UrL string store in "imageName" variable successfully in showImage method.
I need to do the same in this method "segmentedControlIndexChanged" but i cant get the variable "imageName".
Is there anyway i can declare the IBAction method to work similarly as the showImage method?
I Tried ->" -(IBAction) segmentedControlIndexChanged:(NSString *)imageName{} " but it cant work, i'm unable to get the variable "imageName".
- (void) showImage:(NSString *)imageName
{
NSData *imageData;
//NSString * string1 = [NSString stringWithFormat:imageName];
imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageName]];
//NSLog(#"%#",imageName);
image = [[UIImage alloc] initWithData:imageData];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
if(image.size.height+20 >= 224)
{
[scrollview setContentSize:CGSizeMake(289, image.size.height + 20)];
}
else {
[scrollview setContentSize:CGSizeMake(289, 224)];
}
}
////////
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
image = [UIImage imageNamed:image1name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
if(image.size.height+20 >= 224)
{
[scrollview setContentSize:CGSizeMake(289, image.size.height + 20)];
}
else {
[scrollview setContentSize:CGSizeMake(289, 224)];
}
break;
case 1:
image = [UIImage imageNamed:image2name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
[scrollview setContentSize:CGSizeMake(289, image.size.height+20)];
break;
case 2:
image = [UIImage imageNamed:image3name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height+1)];
[scrollview setScrollEnabled:YES];
[scrollview setContentSize:CGSizeMake(289, image.size.height+20)];
break;
default:
break;
}
}
EDIT
I have encountered Bad Access error, anyone knows what does it mean or can anyone show me some ways to solve it?
No, an IBAction can only have one of the following three signatures in iOS:
- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
EDIT
You could extend UIButton to store the value you need, like:
#interface MyButton : UIButton {
}
#property (nonatomic, retain) NSString *url;
#end
...
#implementation MyButton
#synthesize url;
#end
...
- (void)buttonTapped:(id)sender {
MyButton *button = (MyButton *)sender;
UIImage *image = [UIImage imageNamed:button.url];
...
}
EDIT
You can use tags to differentiate between different senders, like
enum {
ButtonOneTag = 128,
ButtonTwoTag,
...
}
...
- (void)buttonTapped:(id)sender {
UIButton *button = (UIButton *)sender;
switch(button.tag) {
case ButtonOneTag:
NSLog(#"Button One Tapped");
break;
case ButtonTwoTag:
NSLog(#"Button Two Tapped");
break;
}
You can also just compare the sender to ivars for the buttons like so:
- (void)buttonTapped:(id)sender {
//assuming buttonOne and buttonTwo are IBOutlets on this class
if (sender == self.buttonOne) {
NSLog(#"Button One Tapped");
else if (sender == self.buttonTwo) {
NSLog(#"Button Two Tapped");
}
...
}