電子書籍の厳選無料作品が豊富!

xcodeのobjective-cで書いています。

UIButtonをプログラムで複数生成し、
その後別のボタンを作成し、そのボタンを押したら任意のボタンを削除(隠すのではなく)する方法を模索しています。

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

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

UIButton *bt = [UIButton buttonWithType:UIButtonTypeRoundedRect];

bt.frame = CGRectMake(20.0f, 20.0f + (i * 25),
20.0f, 20.0f);

bt.tag = i;


[bt addTarget:self
action:@selector(pushBt:)
forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt];

}
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)pushBt:(UIButton *)sender {

[sender removeFromSuperview];
}

押したボタンを消す事はできるようなのですが、
一度に全て消す、tagの1と2を消す等の方法や考え方などご教授お願いします。

A 回答 (1件)

配列を用いた方法です。



@implementation ViewController{
NSMutableArray *btnIndex;
}

- (void)viewDidLoad{
//配列の初期化
btnIndex = [[NSMutableArray alloc]init];
for(int i = 0; i < 5; i++){
UIButton *bt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
(省略)
[self.view addSubview:bt];
//配列にボタンを追加
[btnIndex addObject:bt];
}
//別のボタン作成
UIButton *anyBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[anyBtn addTarget:self
action:@slector(removeBtn:)
forControlEvents:UIControlEventTouchUpInside];
(略)
}

- (void)removeBtn:(id)sender{
//全消し,if文追加で1番目と2番目消し
for(int i = 0; i < [btnIndex count]; i++){
UIButton *btn = [btnIndex objectAtIndex:i];
// if(i == 0 || i == 1){
[btn removeFromSuperview];
// }
}
}

他で使わなければ配列のリスト削除も。
    • good
    • 0
この回答へのお礼

遅くなりました。とてもわかりやすく回答頂きありがとうございました。

お礼日時:2013/08/21 21:41

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!