[英]Change properties of programmatically created UIButton in a different IBAction
我有一種方法可以通過編程方式創建多個UIButton
實例並將其放置在視圖中。 另一個IBAction
在觸發時需要更改其中一個UIButton
的背景顏色,但是當我嘗試對其進行操作時,它告訴我在UIView *
類型的對象上找不到該Property UIView *
使用以下命令創建按鈕:
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];
當我嘗試從其他IBAction訪問它時,例如:
button.backgroundColor = [UIColor blackColor];
它失敗,並出現上述錯誤。
任何幫助深表感謝。 我看到了另一個建議創建一個數組作為IBOutlet
並以這種方式訪問它的答案,但我想知道是否還有另一種方法。
謝謝!
全局聲明此button
並標識tag
每個按鈕,就像或假設這樣
UIButton * button, *button2; // declare in your view controller.h
- (IBAction)butaction:(id)sender; //this is your color change method;
在您的View Controller.m中,無論您在何處添加此按鈕
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag=10; //this is important
[self.view addSubview:button];
button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.tag=20; //this is important
[self.view addSubview:button1];
//here ur color change method
- (IBAction) butaction:(UIButton*)sender {
switch (sender.tag)
{
case 10:
[button setBackgroundColor:[UIColor blackColor]];
break;
case 20:
[button1 setBackgroundColor:[UIColor blackColor]];
break;
default:
break;
}
}
試試這個,可能會有所幫助
for (int index=1; index<=5; index++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(ButtonClickedFunction:) forControlEvents:UIControlEventTouchUpInside];
button.tag= index;
[view addSubview:button];
};
在IBAction中實現
-(IBAction)ButtonClickedFunction:(UIButton *)button{
button.backgroundColor = [UIColor blackColor];
}
注意:在此,我創建了5個按鈕,但未設置框架。 請根據您的要求設置框架。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.