Pass Button object to method
I am trying to write a generic method that would allow me to pass the following: "x", "y" "object" and then have it move. Currently I have this:
-(void) changeObjectLocations: (integer_t) xSpot: (integer_t) ySpot: (id) sender {
if (![sender isKindOfClass:[UIButton class]])
{
UIButton *myObject = (UIButton *)sender;
[UIView animateWithDuration:1.5
animations:^{
CGRect newFrame = myObject.frame;
newFrame.origin.x = xSpot;
newFrame.origin.y = ySpot;
myObject.frame = newFrame;
}];
}
else if (![sender isKindOfClass:[UILabel class]])
{
UILabel *myObject = (UILabel *)sender;
[UIView animateWithDuration:1.5 animations:^{
CGRect newFrame = myObject.frame;
newFrame.origin.x = xSpot;
newFrame.origin.y = ySpot;
myObject.frame = newFrame;
}];
}
}
I then want to call it like so:
-(void) orientationBlockLandscape {
[self changeObjectLocations: 456 :282 : btn1] ;
[self changeObje开发者_Python百科ctLocations: 391 :227 : lblTitle] ;
}
Although it is working, on compile I get the following warning:
SecondViewController.m:33: warning: 'SecondViewController' may not respond to '-changeObjectLocations:::'
Is there a better way I can/should be passing the object? Thanks in advance for any and all help.
Geo...
Based on the warning outputted, it sounds like you didn't define changeObjectLocations
in the header of your SecondViewController -- or it's not the same signature as what you've implemented.
The compiler looks for selectors which are the method definitions with the variables and return removed.
So a method like:
-(void) setObject:(id) anObject forKey:(NSString *) keyname;
... would have a selector of:
setObject:forKey:
Therefore, your method of:
-(void) changeObjectLocations: (integer_t) xSpot: (integer_t) ySpot: (id) sender
... will have a selector of:
changeObjectLocations:xSpot:ySpot:
Note that the parameter names are part of the selector so:
changeObjectLocations:xSpot:ySpot:
and
changeObjectLocations:::
.. are two entirely separate selectors which represent two entirely separate methods.
Although it is legal in the language to use parameters without names e.g. ":::" it is very, very poor practice largely because it is to easy to get a naming collision. Being explicit not only makes the code easier to read and maintain but makes it easier for the complier and runtime to function.
精彩评论