自定义UIButton无法正常工作

时间:2011-08-28 20:57:02

标签: ios objective-c uibutton

在查看这个简单主题的帖子后,我仍然无法弄清楚我在这里做错了什么。我试图使按钮在同一个viewController中循环执行相同的操作。

当视图进入屏幕时,按钮不会单击(或者至少NSLog不会写入第一次输入此代码时所执行的控制台。)

- (IBAction)answer: (id) sender{
NSLog(@"The Number is: %d\n",qNumber);
qNumber+=1;

UIView *newView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[newView setUserInteractionEnabled:TRUE];
UIImage *buttonImage = [UIImage imageNamed:@"pink_button.png"];
UIImageView *buttonImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(23, 294, 72, 37)] autorelease];
[buttonImageView setImage:buttonImage];

UILabel* buttonLabel = [[[UILabel alloc] initWithFrame:CGRectMake(23, 294, 72, 37)] autorelease];
buttonLabel.text = @"newLow";
buttonLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size: 15.0];
buttonLabel.textColor = [UIColor blackColor];
buttonLabel.backgroundColor = [UIColor  clearColor];
buttonLabel.textAlignment = UITextAlignmentCenter;

lowButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[lowButton addSubview:buttonImageView];
[lowButton addSubview:buttonLabel];
[lowButton addTarget:self action:@selector(answer:) forControlEvents:UIControlEventTouchUpInside];

[newView addSubview:lowButton];
self.view = newView;
}

感谢您提供的任何帮助......即使我错过了一些简单的事情: - )

最新更新代码:

lowButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[newView addSubview:buttonImageView];
[newView addSubview:buttonLabel];
[lowButton addTarget:self action:@selector(answer:) forControlEvents:UIControlEventTouchUpInside];

[newView addSubview:lowButton];
[self.view bringSubviewToFront:lowButton];
self.view = newView;

当按下按钮时,它仍然不会输入动作代码。

2 个答案:

答案 0 :(得分:1)

你的按钮需要一个框架。你无法点击无框按钮。

lowButton.frame = CGRectMake(23, 294, 72, 37);

此外,当您向该按钮添加标签和图像时,它们的框架应具有x和y 0。

UIImageView *buttonImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 72, 37)] autorelease];
...
UILabel* buttonLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 72, 37)] autorelease];
...

但是,如果有UIBmage和UILabel的标签和背景视图属性,我可以问你为什么要添加新的UIImageView和UILabel?

编辑这里有一个清理过的代码:

UIView *newView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

lowButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[lowButton setImage:[UIImage imageNamed:@"pink_button.png"] forState:UIControlStateNormal];
[lowButton setTitle:@"newLow" forState:UIControlStateNormal];
[lowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[lowButton.titleLabel setFont:[UIFont boldSystemFontOfSize:15.0]];
[lowButton addTarget:self action:@selector(answer:) forControlEvents:UIControlEventTouchUpInside];

[newView addSubview:lowButton];
self.view = newView;

注意我也删除了[newView setUserInteractionEnabled:TRUE];,因为它是默认启用的。

答案 1 :(得分:0)

您的自定义按钮的子视图覆盖了按钮,因此不会获得任何点击。 尝试将所有子视图添加到newView而不是lowButton(包括lowButton本身),然后调用

[self.view bringSubViewToFront:lowButton];
相关问题