I'm trying to change the title of a button when the user press on it with the following code:
- (IBAction) hideKB: (UIButton *) sender {
sender.titleLabel.text = @"↓";
}
But when I click the app crashes and I can't understand why.
Removing the sender stuff, the button 开发者_开发问答works with no problems.
The correct method signature for an action is
- (IBAction)action:(id)sender
Your app is crashing because your object is being sent a message it doesn't understand.
Try replacing your code with something along the lines of:
- (IBAction)hideKB:(id)sender {
UIButton *button = (UIButton *)sender;
[button setTitle:@"↓" forState:UIControlStateNormal];
}
As you may notice I've also changed the line that sets the button title. This is because you should never manipulate a UIButton
's titleLabel
property directly, but rather you should be using the appropriate setter method as shown above.
Edit: To clarify, most controls will allow you to use dot notation to edit the text
property of their titleLabel
. However, UIButton
instances support different titles (as well as images and background images) depending on the state they're in.
If you're wondering why a UIButton
could be in one of several different states, a good example you often see is buttons that are "greyed out". What this means is that those buttons are in the UIControlStateDisabled
state. You can find a list of all the possible states for a control in the documentation.
Try using
- (void)setTitle:(NSString *)title forState:(UIControlState)state
e.g.
[sender setTitle:"↓" forState:UIControlStateNormal];
you can try with:
[(UIButton *)sender setTitle: @"↓"" forState: UIControlStateNormal];
For more information, you can refer to setTitle:forState: in UIButton Class Reference
Hope this helps.
精彩评论