0

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

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

4

2 回答 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);
}

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

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

于 2018-02-22T17:47:30.807 回答
-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;
于 2018-02-22T18:17:56.087 回答