How to Animate a Button in XCode [duplicate] - objective-c

I have two PNGs I want to use as a button. How can I animate a UIButton by switching rapidly between these two images?

You can use animationImages property of your button's imageView:
myButton.imageView.animationImages =
[NSArray arrayWithObjects:[UIImage imageNamed:#"image1.png"],
[UIImage imageNamed:#"image2.png"],
nil];
myButton.imageView.animationDuration = 0.5; //whatever you want (in seconds)
[myButton.imageView startAnimating];
Your button will switch between your two images.
EDIT: As #tidbeck pointed the button needs to have an image assigned to create the imageview property.

Normally for a button you can set three "live" states:
- Normal
- Highlighted
- Selected
I don't know if this can help, but if you set one image to "Normal" and the other image to "Highlighted" you can see the two images while pushing the button.
I don't know if this effect is enough for you.

This small example shows how to set a UIButton to show an indefinite animation of a heart beating.
I have added 8 images into the Assets.xcassets, and named them like this: heart1, heart2, ..., heart8.
private func showHeartedAnimation() {
var images = [UIImage]()
for i in 1...8 { images.append(UIImage(named: "heart\(i)")!) }
self.heartButton.setImage(UIImage.animatedImage(with: images, duration: 0.2), for: .normal)
}
If you want to disable the animation at some point, just assign a simple UIImage to the same button.

Related

Arranging programmatically created NSButtons

I have an array that varies in size. I want to create NSButtons for each element in a Mac OSX Application. So say this is the array: "thing1", "thing2", "thing3", then I want three buttons on the screen titled "button1", "button2", "button3" respectively.
This obviously needs to be done programmatically. I do know how to create buttons programmatically and how to give them a fixed position.
But this cannot be the solution. How would I make the whole thing dynamic, so that no matter how many buttons are going to be created, it won't lead to massive UI issues? (So basically: place all buttons next to another within a certain container for example)
Thank you.
you can create button programmatically this way:
NSButton *myButton = [[[NSButton alloc] initWithFrame:NSMakeRect(x, y, width, height)] autorelease];
[[windowOutlet contentView] addSubview: myButton];
[myButton setTitle: #"Button title!"];
[myButton setButtonType:NSMomentaryLightButton]; //Set what type button You want
[myButton setBezelStyle:NSRoundedBezelStyle]; //Set what style You want
[myButton setTarget:self];
[myButton setAction:#selector(buttonPressed)];
}
-(void)buttonPressed {
NSLog(#"Button pressed!");
//Do what You want here...
}
I think you need to use horizontal NSStackView for this. Each item will be a custom NSView (create custom nib) with buttons and elements as its subviews. For right arranging controls inside the item use AutoLayout.
For dynamically placing views you should use constraints. This way you can set up relationship's between your views, instead of placing them at fixed positions. Check out the documentation over here:
https://developer.apple.com/library/prerelease/mac/documentation/AppKit/Reference/NSLayoutConstraint_Class/
There are a few possible approaches.
1) NSStackView
A new-ish class (appeared in 10.9) which handles horizontal or vertical stacking of subviews.
2) Constraints
Constraints allow you to define views' spatial relationships to one another, but they're most easily managed in Interface Builder and can be a bit complicated to work with programmatically.
3) Setting each button's frame in code
With a fairly straightforward loop, you can position the buttons how you like. This is the most "manual" of the three approaches, but also arguably the most clear and predictable. Here's an example of a method which will position buttons.
- (void)arrangeViews:(NSArray <NSView *> *)views startingAt:(NSPoint)startPt spacing:(NSSize)spacing
{
NSPoint loc = startPt;
for (NSView *view in views) {
NSRect viewFrame = view.frame;
viewFrame.origin = loc;
view.frame = viewFrame;
loc.x += spacing.width;
loc.y += spacing.height;
}
}
If you want to arrange 3 buttons vertically, each one 50 pixels apart, then you'd call the method like this:
[self arrangeViews:#[btn0, btn1, btn2] startingAt:NSMakePoint(100,100) spacing:NSMakeSize(0,-50)];

set both backIndicatorImage and backIndicatorTransitionMaskImage on backbarbutton in IOS7 didnot show particular image

I searched all the topics about backbarbutton custom, but seems failed to find answers about my problem on backbarbutton.
To keep the property called interactivePopGestureRecognizer of UINavigationController, using leftBarButton to replace backBarButton is not a valid solution. But I want to custom the backbarbutton with a image, so I use the following code in my controller ViewDidLoad:
UIBarButtonItem * btnBack = [[UIBarButtonItem alloc]init];
btnBack.title = #"";
self.navigationController.navigationBar.backIndicatorImage = [UIImage imageNamed:#"backBtn"];
self.navigationController.navigationBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:#"backBtn"];
self.navigationItem.backBarButtonItem = btnBack;
when I run my project, it shows just a blue rectangle in the place where backBarButton always show.
But the original image just like the system barbutton that called reply.
However, it has a different effect, just change to the image named "Drinks" which is a black image that show a glass of juice.
after run my project the place where always show backBarButton show a blue image just like "Drinks".
what happend! How can I custom my backBarButton with the giving image named backBtn.png, is there anyone can help me? Thanks in advance! For image submit has been reject, I discrible my problem in words.
The Image has be transparent where there should be nothing to be drawn. It should be opaque where the content of the image will be drawn. At least that worked for me. The final color will be tinted by the navigationbar's tintColor anyway.

Button above image with zoom objective c

I need to show an image, and above it some buttons that correspond to certain clickable areas of the image, the problem is that the image has zoom, and when i zoom the image, the buttons do not stay in the same place as the picture. The solution was to use the class ImageScrolView, used in the example of Apple PhotoScroller. The button appears exactly in the right place, regardless of zoom.
Just like the example, i use a ScrollView to display multiple images, these images are shown by class ImageScrollView.
This class declares one UIView in the .H file, but in the implementation file, the method that displays the image, convert the UIView into a UIImageView
imageView = [[UIImageView alloc] initWithImage: image];
then create my button and add to the imageView.
amazon = [UIButton buttonWithType: UIButtonTypeRoundedRect];
amazonia.frame = CGRectMake (92,240,109,142);
[amazon addTarget: self action: # selector (selectState :) forControlEvents: UIControlEventTouchUpInside];
[imageView addSubview: amazon];
My problem is that the button does not respond to button events, it appears in the right place and everything, but does not respond to button events.
Any ideas? Ideias on how to implement those clickable areas on the image are welcome too.
make sure to set imageView.userInteractionEnabled = YES!
Hope that helps.

How to handle autoresizing on UIButton elements which has been created dynamically

I create some buttons dynamically on my view and i decide their frames according to some of my JSON respone parameters. But i want to autoresize them when the device(dsimulator) rotates. I can easily do this on interface builder but can't do anything on dynamic ones. Can someone help?
EDIT
Here is a snipped of my code
if (button.tag==1) {
button.frame = CGRectMake(30.0f, yPosition, 200.0f, buttonHeight);
}
if (button.tag==2) {
button.frame = CGRectMake(280.0f, yPosition, 200.0f, buttonHeight);
}
if (button.tag==3) {
button.frame = CGRectMake(530.0f, yPosition, 200.0f, buttonHeight);
}
There is no problem when using Portraid mode but when it rotates to Landscape a big empty area stays on the right side of the screen. How can i fix this?(I mean, when i rotate, i want the buttons got to the center of the scren's width)
EDIT:
I played with autoresizing on Size Inspector(Xcode 4.3) with my xib file and it works great, but whatever i did i couldn't resize the dynamically created buttons after rotation. I tried almost all of AutoresizingMask enums of UIView but nothing changes. Can someone please help
You can define by code what was the expected behavior when the device is rotated.
You can take a look at: http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html
and
http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/c/tdef/UIViewAutoresizing
You need to set the button behavior when you add it like:
[button setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
The attributes you've set up in your interface builder file are the UIViewAutoresizing attributes.
Take a look at this documentation from Apple on the UIView class (which your button is a subclass of); look for the UIViewAutoresizing attribute. That's the one you'll want.
Update: Here's a snippet of code for an MKMapView that uses this ability:
mainMapView = [[MKMapView alloc] initWithFrame:CGRectMake(20, 239, 280, 122)];
[mainMapView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
With UIViewAutoresizingFlexibleTopMargin, the map view moves down when the user answers the phone --- it fixes the map's position relative to the top of the screen.
Dig around in the documentation and you'll find the autoresizing mask that works best for your situation.

Adding array of images to UIbuttons

I have some uiButtons in my table view and i want to load them with images which i get from an array. But i am not able to add images to the button using the array and it is crashing my entire app. Can anyone provide me the solution of how to add images to buttons in table view using Array of Images.Any help will be appreciated.
This method is called from a loop where i am passing a button as the parameter
-(void)setImage1:(UIButton *)button
UIButton *newButton=[[UIButton alloc]init];
newButton=button;
[newButton setImage:[NSString stringWithFormat:#"%d.png", j] forState:UIControlStateNormal]; j++; }
Thanks,
Christy
//Create an image
UIImage *image= [UIImage imageWithContentsOfFile:#"image.jpg"];
// Set image for the button
[button setBackgroundImage:image forState:UIControlStateNormal];
Show us some code at least for more help.
You should not create the button within that method. Create it in ViewDidLoad, or even better, in Interface builder. If you create a button programatically you will have to also make sure you enable user interaction, and then set its frame and add it to the view.