How to place a button on animation image in iOS? - ios

In my app, I have an array of image, which is getting animated for every second.
I used the following code,
animateArrayImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"gallery-img-1.png"],
[UIImage imageNamed:#"gallery-img-2.png"],nil];
animateImageView.animationImages = animateArrayImages;
animateImageView.animationDuration = 1.0f;
animateImageView.animationRepeatCount = 0;
[animateImageView startAnimating];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(20, 20, 20, 20)];
[self.view addSubview:button];
But I am getting an output like this
The button is getting displayed in the background of the image.
But I want to display it befor the image

If you want to bring the button on top of the image, you can call the following method after addSubview:
[self.view bringSubviewToFront:button];

Related

Moving a UIImageView with a UIButton

I am rather new to Xcode and iOS development but have been enjoying the challenge so far.
I have run into an issue where I am attempting to move a UIImageView I have created programmatically on top of a MapBox mapView.
I would like to move this UIImageView with a UIButton by a measure of pixels, with the UIButton being on top of the mapView.
This is the code I have so far in my ViewController.m:
[self.view addSubview:mapView];
UIImageView* ship;
ship=[[UIImageView alloc] initWithFrame:CGRectMake(150, 200, 40, 40)];
UIImage * image;
image=[UIImage imageNamed:#"spaceShip"];
[ship setImage:image];
ship.alpha = 0.75;
[self.view addSubview:ship];
UIButton *upButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
upButton.frame = CGRectMake(150, 250, 40, 40);
upButton.userInteractionEnabled = YES;
[upButton setTitle:#"UP" forState:UIControlStateNormal];
[upButton addTarget:ship action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:upButton];
}
- (IBAction)moveUp {
ship.center = CGPointMake(ship.center.x, ship.center.y -10);
}
Could anyone show me how to get this upButton to recognize and move my UIImageView?
One problem is that ship is a local variable that you create in the first block of code. When that code block goes out of scope, ship will be nil, so when you try to set it's center in the button method, it won't work. You need to create a property for ship, and use that instead.
Your other problem is that when you add the action to your button, you call it buttonPressed:, but the method you implemented is moveUp. So, if you create a property called ship, then your action method should be,
- (void)buttonPressed:(UIButton *) sender {
self.ship.center = CGPointMake(self.ship.center.x, self.ship.center.y -10);
}

UIButton in code

I need to add a gesture (move, rotate, scale) to a UIButton.
I created the button in code, but I don't know how to use it.
If the button is touched I want to move, scale or rotate.
Here is my code:
-(void)addButton{
UIScrollView *scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,480)];
scrollview.showsVerticalScrollIndicator=YES;
scrollview.scrollEnabled=YES;
scrollview.userInteractionEnabled=YES;
[self.view addSubview:scrollview];
scrollview.contentSize = CGSizeMake(self.view.bounds.size.width,1000.0);
buttonImage1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonImage1.frame = CGRectMake(100, 20, 100, 100);
UIImage *btnImage1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:adres1]]];
[buttonImage1 setImage:btnImage1 forState:UIControlStateNormal];
[scrollview addSubview:buttonImage1];
buttonImage2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonImage2.frame = CGRectMake(100, 180, 150, 150);
UIImage *btnImage2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:adres2]]];
[buttonImage2 setImage:btnImage2 forState:UIControlStateNormal];
[scrollview addSubview:buttonImage2];
buttonImage3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonImage3.frame = CGRectMake(100, 450, 194, 146);
UIImage *btnImage3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:adres3]]];
[buttonImage3 setImage:btnImage3 forState:UIControlStateNormal];
[scrollview addSubview:buttonImage3];
}
-(void) move
{
}
I need to add a gesture (move, rotate, scale) to a UIButton.
I'm not sure I understand what you mean about adding a gesture. Right now, your buttons aren't set up to do anything at all.
I created the button in code, but I don't know how to use it.
You need to add a target and action to your button. When a button is tapped, it sends an action message to some other object, which is its target. To set up a button, you need to add a target and action using the -addTarget:action:forControlEvents: method inherited from UIControl. If you want the button to send a move message to the same object that's creating the button, you'd change your addButton method to include this:
[buttonImage1 addTarget:self action:#selector(move) forControlEvents:UIControlEventTouchUpInside];

How can i make clickable uiimage?

I have one menubar as a uiimage. I want to make 5 menu on this menubar are clickable and link to another view. Can anyone tell me the way i can do that? I found people using uibutton on the uiimage, Is that fine for me and how can i separate the menu bar to 5 pieces.
Thanks for both rmaddy and Brent Royal-Gordon
I decided to use the uiimage as a menubar background and add the uibutton on it. i try some thing like this:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"MOVIE" ofType:#"MP4"]];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleNone;
moviePlayer.repeatMode = MPMovieRepeatModeOne;
moviePlayer.shouldAutoplay = YES;
moviePlayer.scalingMode = MPMovieScalingModeFill;
[moviePlayer.view setFrame:CGRectMake(0,0,1330,320)];
[scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setContentSize:CGSizeMake(1330,320)];
[scrollView setScrollEnabled: YES];
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
[scrollView addSubview:moviePlayer.view];
[self.view addSubview:scrollView];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:image.frame];
UIImage *menubar = [UIImage imageNamed:#"BG.jpg"];
imageView = [[UIImageView alloc] initWithImage:menubar];
imageView.contentMode = UIViewContentModeScaleToFill;
imageView.frame = CGRectMake(0, 258, imageView.frame.size.width, 25);
[self.view addSubview:imageView];
[imageView setUserInteractionEnabled:YES];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0,258,30,25)];
[btn addTarget:self action:#selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:#"HOME" forState:UIControlStateNormal];
[imageView addSubview:btn];
but the button is not visible on screen when i run on the simulator. What did i do wrong?
Using a gesture recognizer is a bad idea because:
It forces you to interpret the touch areas for each submenu yourself.
It's opaque to VoiceOver.
It doesn't show a highlight when the user touches a button. These sorts of highlights help the user understand what the user interface is doing, so they're very valuable.
What you should do is split the single image into five in a graphics tool like Photoshop, and make each of these slices the image of a UIButton. You'll need to design highlighted states for these images (shown when one of them is held down), but you should be doing that anyway.
If you must slice the image in code, you can do that by using UIGraphicsBeginImageContextWithOptions(size, NO, 0.0) and drawing your big image using drawAtPoint: with an appropriate offset to get the slice you want, but 99.99999% of the time, it'll make more sense to slice the images once on your big, beefy, wall-plug-powered Mac than every time your app runs on a tiny, slow, battery-powered iOS device.
Use a UITapGestureRecognizer with the UIImageView containing your image. You will need to set the userInteractionEnabled property to YES on the image view.
When you get the tap event, look at where in the view the tap occurred. Based on the location, perform one of the five menu actions.
If you want more control, you may be better off splitting the image into 5 and creating 5 UIButton instances instead.
Why you add it the buttons to image view ? Just adding it to the View. It will solve the problem(as i understand).
[imageView addSubview:btn];
Try like this
[self.view addSubview:btn];
Hope this helps
issue is with the Width of the button.Try
this
[btn setFrame:CGRectMake(0,258,100,50)]
(increase width to 100)
and you may need to change the title colour if your background is white
[btn setTitleColor:[UIColor blackColor] forState:
UIControlStateNormal];
you Can first add button view then add imageview on the button please see bellow code :
//Add first button
UIButton *btnImage = [UIButton buttonWithType:UIButtonTypeCustom];
btnImage.frame = CGRectMake(0, 4, 60, 56);
btnImage.backgroundColor = [UIColor colorWithRed:231.0f/255.0f green:232.0f/255.0f blue:234.0f/255.0f alpha:1.0];
btnImage.layer.borderColor = [UIColor colorWithRed:183.0f/255.0f green:184.0f/255.0f blue:186.0f/255.0f alpha:1.0].CGColor;
btnImage.layer.borderWidth = 1.0f;
// Add imageview on button
UIImageView *yourImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[yourImageView setImage:[UIImage imageNamed:#"myimage.png"]];
yourImageView.center = CGPointMake(btnImage.frame.size.width/2, btnImage.frame.size.height/2);
[btnImage addSubview:yourImageView];
[self.view addSubview:btnImage];

UIButton Image + Text IOS

I need a UIButton with image & text. Image should be in the top & text comes under the image both should be clickable.
I see very complicated answers, all of them using code. However, if you are using Interface Builder, there is a very easy way to do this:
Select the button and set a title and an image. Note that if you set the background instead of the image then the image will be resized if it is smaller than the button.
Set the position of both items by changing the edge and insets. You could even control the alignment of both in the Control section.
You could even use the same approach by code, without creating UILabels and UIImages inside as other solutions proposed. Always Keep It Simple!
EDIT: Attached a small example having the 3 things set (title, image and background) with correct insets
I think you are looking for this solution for your problem:
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:#"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:#"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:#selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like
...the rest of the customisation of the button is your duty now, and don't forget to add the button to your view.
UPDATE #1 and UPDATE #2
or, if you don't need a dynamic button you could add your button to your view in the Interface Builder and you could set the same values at there as well. it is pretty same, but here is this version as well in one simple picture.
you can also see the final result in the Interface Builder as it is on the screenshot.
Xcode-9 and Xcode-10 Apple done few changes regarding Edge Inset now, you can change it under size-inspector.
Please follow below steps:
Step-1:
Input text and select image which you want to show:
Step-2:
Select button control as per your requirement as shown in below image:
Step-3:
Now go-to size inspector and add value as per your requirement:
swift version:
var button = UIButton()
newGameButton.setTitle("Новая игра", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50
In my case, I wanted to add UIImage to the right and UILabel to the left. Maybe I can achieve that by writing code (like the above mentioned), but I prefer not to write code and get it done by using the storyboard as much as possible. So this is how did it:
First, write down something in your label box and select an image that you want to show:
And that will create a button looking like this:
Next, look for Semantic and select Force Right-to-Left (If you don't specify anything, then it will show the image to the left and label to the right like the above image):
Finally, you'll see UIImage to the right and UILabel to the left:
To add space between a label and an image, go to the Size inspector and change those values depending on your requirement:
That's it!
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
but following code will show label above and image in background
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
There is no need to use label and button in same control because UIButton has UILabel and UIimageview properties.
Use this code:
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(0, 10, 200, 52)];
[sampleButton setTitle:#"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:#"redButton.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton]
You should create custom imageview for image and custom label for text and you add to your button as subviews. That's it.
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);
[yourButton addTarget:self action:#selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:#"images.jpg"];
[yourButton addSubview:imageView1];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = #"ButtonTitle";
[yourButton addSubview:label];
For testing purpose, use yourButtonSelected: method
-(void)yourButtonSelected:(id)sender{
NSLog(#"Your Button Selected");
}
I think it will be helpful to you.
Use this code:
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.imageView.frame=CGRectMake(0.0f, 0.0f, 50.0f, 44.0f);///You can replace it with your own dimensions.
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 35.0f, 50.0f, 44.0f)];///You can replace it with your own dimensions.
[button addSubview:label];
I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :
-(void)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.
Make UIImageView and UILabel, and set image and text to both of this....then Place a custom button over imageView and Label....
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"search.png"]];
imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
[self.view addSubview:imageView];
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = #"raj";
[self.view addSubview:yourLabel];
UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:#selector(#"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];
It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal.
That's it.
[btn setBackgroundImage:[UIImage imageNamed:#"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:#"Click Me" forState:UIControlStateNormal];

UIButton in IOS responds to first touch and then does not respond to any subsequent touch events

I have created a UIButton programmatically that correctly changes background color as desired when button is touched down for the first time. After that, the button does not respond to any subsequent touch events.
I have instrumented the color change method with NSLog and this method is not called after the first touch, even though the button visually appears to respond to subsequent touches on the iPhone screen. It seems the subsequent touches are not actually triggering any event (eg. TouchDown), but I can't figure out why not.
I have searched every post on sof related to this issue, but none of the answers seem to solve my problem.
The button is declared in the header file as:
UIButton *playerOneButton;
UIButton *playerTwoButton;
Here is the button initialization code that I use after the UIViewController loads:
- (void)viewDidLoad
{
[super viewDidLoad];
//Create initial view of Button One before any selection is made
playerOneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
playerOneButton.frame = CGRectMake(5.0f, 20.0f, 149.0f, 31.0f);
[playerOneButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15.0]];
[playerOneButton setTitle:playerOneName forState:UIControlStateNormal];
[self.view addSubview:playerOneButton];
//Create initial view of Button Two before any selection is made
playerTwoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
playerTwoButton.frame = CGRectMake(166.0f, 20.0f, 149.0f, 31.0f);
[playerTwoButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15.0]];
[playerTwoButton setTitle:playerTwoName forState:UIControlStateNormal];
[self.view addSubview:playerTwoButton];
// Add correct names to both buttons
[playerOneButton setTitle:playerOneName forState:UIControlStateNormal];
[playerTwoButton setTitle:playerTwoName forState:UIControlStateNormal];
// Link buttons to methods that will toggle colors between Green for selected button and Red for unselected button
[playerOneButton addTarget:self action:#selector(setPlayerOneButtonStatus) forControlEvents:UIControlEventTouchDown];
[playerTwoButton addTarget:self action:#selector(setPlayerTwoButtonStatus)
forControlEvents:UIControlEventTouchDown];
}
and the method that is invoked to actually change the colors:
-(void) setPlayerOneButtonStatus;
{
playerOneButton.selected = YES;
// Load colored images
UIImage *imageGreen = [UIImage imageNamed:#"button_green.png"];
UIImage *imageRed = [UIImage imageNamed:#"button_red.png"];
// And create the stretchy versions.
float wGreen = imageGreen.size.width / 2, hGreen = imageGreen.size.height / 2;
UIImage *stretchGreen = [imageGreen stretchableImageWithLeftCapWidth:wGreen topCapHeight:hGreen];
float wRed = imageRed.size.width / 2, hRed = imageRed.size.height / 2;
UIImage *stretchRed = [imageRed stretchableImageWithLeftCapWidth:wRed topCapHeight:hRed];
// Now create button One with Green background color
playerOneButton = [UIButton buttonWithType:UIButtonTypeCustom];
playerOneButton.frame = CGRectMake(5.0f, 20.0f, 149.0f, 31.0f);
[playerOneButton setBackgroundImage:stretchGreen forState:UIControlStateNormal];
[playerOneButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15.0]];
[playerOneButton setTitle:playerOneName forState:UIControlStateNormal];
[self.view addSubview:playerOneButton];
// Now create button Two with Red background color
playerTwoButton = [UIButton buttonWithType:UIButtonTypeCustom];
playerTwoButton.frame = CGRectMake(166.0f, 20.0f, 149.0f, 31.0f);
[playerTwoButton setBackgroundImage:stretchRed forState:UIControlStateNormal];
[playerTwoButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15.0]];
[playerTwoButton setTitle:playerTwoName forState:UIControlStateNormal];
[self.view addSubview:playerTwoButton];
}
You are creating a new playerOneButton in the action method without assigning a target/action to it.

Resources