自定义视图调用时,UIButton不可点击
我是iPhone开发的新手,我需要帮助来理解以下内容,因为我能够使用以下内容创建newView
I am new to iPhone development,I need help in understanding the below,as I am able to create newView using the following
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];
以上代码可以正常工作.但是,当我尝试使用以下方法创建视图时,可以创建视图,但是视图上的按钮不可单击.
Above code is working without any problem. But when I try to create the view using the following, view is created alright, but the button on the view is not clickable.
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];
如果更改以下代码,则还有另一种情况
and there is one another scenario if change the following code
newViewBtn.frame = CGRectMake(newView.frame.origin.x+5
,newView.frame.origin.y+5,60,20);
应用下面的代码崩溃
newViewBtn.frame =CGRectMake(randNumX+5,randNumY+5,60,20);
任何帮助将不胜感激,谢谢.
Any help will be greatly appreciated,thanks in advance.
我已经添加了以下代码
newViewBtn addTarget:self action:@selector(btnclick:)forControlEvents:UIControlEventTouchUpInside];
-(void)btnclick:(id)sender
{
//my code
}
在第一种情况下有效:
我在这里主要担心的是绘制newView时,为什么该视图上的按钮不可单击
My main concern here is when the newView is draw ,why the button on this view is not clickable
这里的问题是下面的行,因为新的子视图必须与父视图一致
Here the problem is the Line below ,As the new child view must be according to the parent view
newViewBtn.frame =CGRectMake(randNumX+5,randNumY+5,60,20);
将上述内容写成如下即可解决问题
writting the above as below solved the problem
newViewBtn.frame =CGRectMake(5,5,60,20);