我在一个方法中设置了 10 个左右的按钮,如下所示:
@implementation MyViewController
UIButton *originalButton;
etc...
- (void)setupButtons
{
originalButton = [UIButton buttonWithType:UIButtonTypeCustom];
[originalButton addTarget:self action:@selector(originalButtonWasPressed:) forControlEvents:UIControlEventTouchUpInside];
originalButton.frame = CGRectMake(20.0, 30.0, 100.0, 39.0);
UIImage *buttonImage = [[UIImage imageNamed:@"originalreg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
UIImage *buttonImageHighlight = [[UIImage imageNamed:@"originalregblue.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
[originalButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[originalButton setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
[self.view addSubview:originalButton];
etc…
}
为了提高效率,我决定将通用代码提取到另一种方法中:
- (void)setupButton:(UIButton *)myButton withSelector:(SEL)selector withX:(CGFloat)x withY:(CGFloat)y withRegImage:(NSString *)regImage withHighlightImage:(NSString *)highlightImage
{
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(x, y, 100.0, 39.0);
UIImage *buttonImage = [[UIImage imageNamed:regImage] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
UIImage *buttonImageHighlight = [[UIImage imageNamed:highlightImage] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[myButton setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
[self.view addSubview:myButton];
}
…并这样称呼它:
- (void)setupButtons
{
[self setupButton:originalButton withSelector:@selector(originalButtonWasPressed:) withX:20.0 withY:30.0 withRegImage:@"originalreg.png" withHighlightImage:@"originalregblue.png"];
etc...
}
这一切都有效,除了我的一个按钮用于隐藏所有其他按钮。在原始设置中,按下“隐藏按钮”按钮会导致其他按钮被隐藏。现在,它们仍然在屏幕上。这是代码:
[self setupButton:hideButtonsButton withSelector:@selector(hideButtonsButtonWasPressed:) withX:20.0 withY:530.0 withRegImage:@"hidebuttonsreg.png" withHighlightImage:@"hidebuttonsregblue.png"];
- (void)hideButtonsButtonWasPressed:(id)sender
{
// hide the buttons
originalButton.hidden = YES;
originalButton.enabled = NO;
etc…
}
我已经确认正在调用此方法并且setHidden/setEnabled
正在执行调用。
任何指点都感激不尽!托尼。