您好我有UIButton
我以编程方式创建但不幸的是它不起作用。当我点击UIButton
时没有任何反应。我不知道是什么问题。任何帮助将不胜感激。
UIButton *connectedStories = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
connectedStories.frame = CGRectMake(10, 10, 1900, 30);
connectedStories.backgroundColor = [UIColor whiteColor];
[connectedStories setTitle:@"Button" forState:UIControlStateNormal];
[connectedStories setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[connectedStories addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
[label setText:storyTitle];
[label1 setText:storyDescription];
[contentView addSubview:backGroundImageView];
[contentView addSubview:connectedStories];
[contentView addSubview:label];
[contentView addSubview:label1];
[viewContainer addSubview:contentView];
return contentView;
- (void)buttonClicked
{
NSLog(@"button clicked");
}
答案 0 :(得分:2)
我认为标签会重复触摸,而不是按钮。 添加userInteractionEnabled = NO;到你的标签。
label.userInteractionEnabled = NO;
label1.userInteractionEnabled = NO;
答案 1 :(得分:0)
尝试将代码的顶部更改为:
CGRect frame = CGRectMake(10, 10, 1900, 30);
UIButton *connectedStories = [[UIButton alloc] initWithFrame:frame];
//set the position of the button
[connectedStories setBackgroundColor:[UIColor whiteColor]];
[connectedStories setTitle:@"Button" forState:UIControlStateNormal];
[connectedStories setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[connectedStories addTarget:nil action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
答案 2 :(得分:0)
可能如下:
[contentView addSubview:backGroundImageView];
[contentView addSubview:connectedStories];
[contentView addSubview:label];
[contentView addSubview:label1];
我确定您需要按以下顺序添加它们:
[contentView addSubview:backGroundImageView];
[contentView addSubview:label];
[contentView addSubview:label1];
[contentView addSubview:connectedStories];
这是因为当您调用addSubview:
时,它会将其添加到子视图的接收者列表的末尾,并且最新的子视图显示在顶部。
查看UIView文档here
未检测到Interaction的原因是您没有将touchEvents传递给其他子视图,因为它们被label1捕获并停在那里。
默认情况下,最后一个subView会捕获所有触摸事件,但不会传递它们。
答案 3 :(得分:0)
在选择器
中的最后一个方法中添加冒号[connectedStories addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[label setText:storyTitle];
答案 4 :(得分:0)
UIButton *custombutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[custombutton addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[custombutton setTitle:@"Click" forState:UIControlStateNormal];
custombutton.frame = CGRectMake(80.0, 110.0, 160.0, 40.0);
custombutton.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f alpha:1];
[custombutton setImage:[UIImage imageNamed:@"hh.png"] forState:UIControlStateNormal];
[view addSubview:custombutton];