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

问题描述 投票:0回答:2

我已经以编程方式向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);
  }
}

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

ios objective-c uibutton uicontrolevents addtarget
2个回答
0
投票

这很好用:

- (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);
}

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

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


-1
投票

让我们更有活力:

-(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;
© www.soinside.com 2019 - 2024. All rights reserved.