在视图中,我使用标签作为按钮的主机。标签已添加到self.view
。两个对象都按预期显示,但不触发按钮中定义的操作。
这是代码:
datelabel = [[UILabel alloc] init];
datelabel.frame = CGRectMake(10, 200, 300, 40);
datelabel.backgroundColor = [UIColor whiteColor];
datelabel.textColor = [UIColor blueColor];
datelabel.font = [UIFont fontWithName:@"Verdana" size: 18.0];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
datelabel.text = [NSString stringWithFormat:@"%@",
[df stringFromDate:[NSDate date]]];
CGRect buttonFrame = CGRectMake( 170, 8, 130, 25 );
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
[button setTitle: @"My Button" forState: UIControlStateNormal];
[button addTarget:self action:@selector(salvarFecha:) forControlEvents:
UIControlEventTouchUpInside];
[button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[datelabel addSubview:button];
[self.view addSubview:datelabel];
这里是按钮动作代码:
- (void)salvarFecha: (id) sender{
NSLog(@"BOTON PULSADO");
}
欢迎任何帮助......
答案 0 :(得分:1)
我从来没有听说过有人添加UIButton作为UILabel的子视图。为什么不像使用datelabel一样将它添加到self.view中?
答案 1 :(得分:0)
在我看来,您需要将userInteractionEnabled
设置为YES
来自UIView.h
:
if set to NO, user events (touch, keys) are ignored and removed from the event queue.
在UILabel.h
中,此字段默认为NO
希望这会对你有所帮助