调用自定义视图时,UIButton无法单击
我是iPhone开发新手,我需要帮助理解下面的内容,因为我能够使用以下内容创建newView
UIView *newView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 30)]; newView.backgroundColor=[UIColor clearColor]; UIButton *newViewBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; newViewBtn.frame = CGRectMake(newView.frame.origin.x+5, newView.frame.origin.y+5,60,20); [newView addSubview:newViewBtn]; [self.view addSubview:newView];
上面的代码工作没有任何问题。 但是当我尝试使用以下内容创建视图时,视图创建正常,但视图上的按钮不可单击。
int randNumX = arc4random() % 150; int randNumY = arc4random() % 200; UIView newView=[[UIView alloc]init]; newView.frame =CGRectMake(randNumX, randNumY, 80, 30); newView.backgroundColor=[UIColor clearColor]; UIButton *newViewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; newViewBtn.frame = CGRectMake(newView.frame.origin.x+5 ,newView.frame.origin.y+5,60,20); [newView addSubview:newViewBtn]; [self.view addSubview:newView];
如果更改以下代码,还有另一种情况
newViewBtn.frame = CGRectMake(newView.frame.origin.x+5 ,newView.frame.origin.y+5,60,20);
使用app下面的代码崩溃
newViewBtn.frame =CGRectMake(randNumX+5,randNumY+5,60,20);
任何帮助将不胜感激,谢谢你提前。
我已经添加了以下代码
newViewBtn addTarget:self action:@selector(btnclick:)forControlEvents:UIControlEventTouchUpInside]; -(void)btnclick:(id)sender { //my code }
它在第一种情况下工作:
我主要关注的是当newView被绘制时,为什么此视图上的按钮不可点击
将自定义子视图添加到UIButton时,必须运行userInteractionEnabled属性。
customView.userInteractionEnabled = NO;
然后添加到您的按钮。
[customButton addSubView:customView];
否则,您的自定义视图会截取按钮之前的触摸事件,因为它已添加到视图堆栈的顶部。
这里的问题是下面的Line,因为新的子视图必须是根据父视图
newViewBtn.frame =CGRectMake(randNumX+5,randNumY+5,60,20);
写下面的内容解决了这个问题
newViewBtn.frame =CGRectMake(5,5,60,20);
你忘了这个:
UIButton *newViewBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; [newViewBtn addTarget:self action:@selector(clickeMe) forControlEvents:UIControlEventTouchUpInside];
请试试这个。
试试以下代码……
int randNumX = arc4random() % 150; int randNumY = arc4random() % 200; UIView newView=[[UIView alloc]init]; newView.frame =CGRectMake(randNumX, randNumY, 80, 30); newView.backgroundColor=[UIColor clearColor]; UIButton *newViewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; newViewBtn.frame = CGRectMake(0,0,60,20); newViewBtn.center = newView.center; [newViewBtn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside]; [newView addSubview:newViewBtn]; [self.view addSubview:newView]; -(void)btnTapped:(id)sender { NSLog(@"btnTapped"); }
我相信你忘了添加目标(单击按钮时调用的函数):
[newViewBtn addTarget:self action:@selector(yourfunction:) forControlEvents:UIControlEventTouchUpInside];
确保您要定位的function存在,否则单击时会崩溃。
- (void) yourfunction { NSLog(@"Click Detected"); }
你需要像这样添加目标……
UIButton *newViewBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; newViewBtn.frame=CGRectMake(newView.frame.origin.x+5,newView.frame.origin.y+5,60,20); [newViewBtn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside]; // ---- add this line..... [newView addSubview:newViewBtn]; -(void)btnPressed:(id)sender { NSLog(@"Btn Pressed"); }