UIButton的自定义视图 - addTarget:动作:forControlEvents:不工作
我的按钮如下UIButton的自定义视图 - addTarget:动作:forControlEvents:不工作
- 创建LABEL1
- 创建LABEL2
- 创建customView(
UIView
) - 添加label1和label2自定义视图
- 创建myCustomButton(
UIButton
) - 在myCustomButton上添加customView
我已经为custom_View,label1和label2做了userInteractionEnable。
然后加入
[myCustomButton addTarget:self action:@selector(OnButtonClick:) forControlEvents:UIControlEventTouchUpInside];
而且
-(void)OnButtonClick:(UIButton *)sender
{
}
但上述功能,甚至当我触摸按钮永远不会被调用。任何解决方案
只是你的代码我的朋友一个小问题,你只需要添加只有一个下面一行到你的代码,忘了setUserInteractionEnabled:NO
到UIView
它可以让你按一下按钮
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[lbl1 setText:@"ONe"];
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)];
[lbl2 setText:@"Two"];
UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 130)];
[view setUserInteractionEnabled:NO];
[view addSubview:lbl1];
[view addSubview:lbl2];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:view];
[btn setFrame:CGRectMake(0, 0, 200, 130)];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
单击方法
-(void)click
{
NSLog(@"%s",__FUNCTION__);
}
你确定视图的'setUserInteractionEnabled'应该是NO?我把它设置为是,然后它工作! – 2014-10-01 18:59:01
是的,因为button是在'self.view'中添加的,而标签是在'view'中的,所以如果你禁用它的用户交互。它没有任何区别,因为按钮和标签位于不同的容器中。 – 2014-10-02 05:53:18
而不是创建customView(UIView的实例),您在CustomViewClicked方法
-(void)customViewClicked:(id)sender
{
UIControl *senderControl = (UICotrol *)sender;
NSLog(@"sender control = %@",senderControl);
}
成也addTarget添加customView作为UIControl的实例的customView,
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(10,10,300,300)];
UIControl *customView = [[UIControl alloc] initWithFrame:CGRectMake(0,0,300,300)];
[customView addTarget:self action:@selector(customViewClicked:) forControlEvents:UIControlEventTouchUpInside];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10,10,100,100)];
[label1 setText:@"Hello How are you ?"];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10,150,100,100)];
[label1 setText:@"I am fine Thnank You!"]
[customView addSubView:lebel1];
[customView addSubView:lebel2];
现在希望它能帮助你。
感谢您的建议。我得到了解决方案形式的其他答案... – Sagrian 2013-05-09 05:24:01
请把您的相关代码放在这里? – 2013-05-08 13:56:10