使用选择器操作将多个UIButtons添加到UIView

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用选择器操作将多个UIButtons添加到UIView相关的知识,希望对你有一定的参考价值。

我已经以编程方式向UIView添加了一些按钮(通过addSubview)。我在这个按钮中添加了一个带有函数的@selector。但是,它们出现在视图中,但是当我单击时,最后一个按钮仅起作用。

进入我的.h:

@property (nonatomic, strong) UIButton * myButton;

进入我的.m

for(int i=0;i<5;i++){

myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(55, 55*i, 30, 30);
myButton.tag = i;
myButton.backgroundColor = [UIColor redColor];
[myButton addTarget:self action:@selector(myaction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:myButton];

}

-(void)myaction:(UIButton *)sender{
  if(sender.tag == 0){
    NSLog(@“uibutton clicked %ld", (long)sender.tag);
  }
}

如何将操作添加到所有按钮?不是最后一个......

答案

这很好用:

- (void)viewDidLoad {
    [super viewDidLoad];

    for(int i=0;i<5;i++){

        UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
        myButton.frame = CGRectMake(55, 55*i, 30, 30);
        myButton.tag = i;
        myButton.backgroundColor = [UIColor redColor];
        [myButton setTitle:[NSString stringWithFormat:@"%ld", (long)i] forState:UIControlStateNormal];
        [myButton addTarget:self action:@selector(myaction:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:myButton];
    }


}

-(void)myaction:(UIButton *)sender{
    NSLog(@"uibutton clicked %ld", (long)sender.tag);
}

您在问题中发布的代码似乎是“这是我的代码看起来像”而不是您的实际代码。当人们试图帮助时,这可能会导致问题。

将来,发布您的实际代码。

另一答案

让我们更有活力:

-(void)viewDidLoad {

 [super viewDidLoad];

 NSInteger height = self.frame.size.height - 5*20; // 5 is the button count 
 and 20 is the padding 
 NSInteger buttonHeight = height/5;
 for(int i=0;i<5;i++){
    UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(55, buttonHeight*i+padding*(i+1), 150, 
     buttonHeight);
    myButton.tag = i;
    myButton.backgroundColor = [UIColor redColor];
    [myButton setTitle:[NSString stringWithFormat:@"%ld", (long)i] 
    forState:UIControlStateNormal];
    [myButton addTarget:self action:@selector(myaction:) 
    forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton];
}}

-(void)myaction:(UIButton *)sender{
 NSLog(@"uibutton clicked %ld", (long)sender.tag);
}

您可以通过计算按钮的高度使其更加动态,如下所示:

NSInteger height = self.frame.size.height - 5*20; 
NSInteger buttonHeight = height/5;

以上是关于使用选择器操作将多个UIButtons添加到UIView的主要内容,如果未能解决你的问题,请参考以下文章

使用动作选择器预设将项目添加到 NSMenu

使用选择器操作向 UIView 添加多个 UIButton

如何将一组 UIButtons 添加到 UIStackview 上?

如何将 UIButtons 添加到我的 TableViewCell? [复制]

将 UIButtons 添加到 ViewDidLoad 上的数组

jquery .on 容器元素附加到多个选择器