4

嗨,我有一个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");
}
4

5 回答 5

2

我认为标签接收触摸而不是按钮。添加 userInteractionEnabled = NO; 到你的标签。

label.userInteractionEnabled = NO;
label1.userInteractionEnabled = NO;
于 2012-05-22T15:36:31.663 回答
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];
于 2012-05-22T15:47:28.873 回答
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 文档

未检测到交互的原因是您没有将 touchEvents 传递给其他子视图,因为它们被 label1 捕获并停在那里。

默认情况下,最后一个 subView 捕获所有触摸事件并且不传递它们。

于 2012-05-23T01:36:07.373 回答
0

在选择器的最后一个方法中添加冒号

[connectedStories addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [label setText:storyTitle];
于 2013-03-15T10:50:23.443 回答
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];
于 2013-12-31T10:38:22.740 回答