I have a method that accepts a sender and is called with a UIbutton. How do I get that object to casted into a UIImageView? Basically how do I re-use the code for the button.
- (IBAction)startClick:(id)sender {
button.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"Pic_1.png"],
[UIImage imageNamed:@"Pic_2.png"],
[UIImage imageNamed:@"Pic_3.png"],
nil];
[button setAnimationRepeatCount:1];
button.animationDuration = 1;
[button startAnimating];
}
My first response is that it’s probably a mistake to do so.
UIButtonandUIImageVieware distinct subclasses ofUIView(andUIButtonis a subclass ofUIControl) so the only things they have in common areUIViewmethods. Ifsenderis really aUIButton, treating it as aUIImageViewis likely to result in errors, such as “unrecognized selector sent to instance” and the like.In general, a cleaner solution is to create a separate method that is the action for a
UIImageView. (Unlike Java, Objective-C and Cocoa prefer to not shoehorn UI response code into a single method based on the event type — rather, you organize the code logically based on the operation that needs to happen.)If you must call this method from both buttons and image views, you can separate the logic like this: