Mar*_*ijn 5 iphone objective-c uibutton uiview
我以编程方式在我的视图中添加了几个UIButtons.单击其中一个按钮后,它们都应该是"removeFromSuperView"或已发布,而不仅仅是一个.
for (int p=0; p<[array count]; p++) {
button = [[UIButton alloc] initWithFrame:CGRectMake(100,100,44,44)];
button.tag = p;
[button setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}
Run Code Online (Sandbox Code Playgroud)
现在这是应该删除所有按钮的部分.不只是一个.
-(void) action:(id)sender{
UIButton *button = (UIButton *)sender;
int pressed = button.tag;
[button removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮我这个!
一种更有效的方法是在创建数组时将每个按钮添加到数组中,然后当按下按钮时,让数组中的所有按钮调用-removeFromSuperView
方法如下:
[arrayOfButtons makeObjectsPerformSelector:@selector(removeFromSuperView)];
Run Code Online (Sandbox Code Playgroud)
然后,您可以将按钮保留在数组中并重复使用,或者调用removeAllObjects
以释放它们.然后你可以稍后再开始填充它.
这使您无需遍历整个视图层次结构来查找按钮.
另一个答案仅供参考:
for (int i = [self.view.subviews count] -1; i>=0; i--) {
if ([[self.view.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) {
[[self.view.subviews objectAtIndex:i] removeFromSuperview];
}
}
Run Code Online (Sandbox Code Playgroud)
NSMutableArray *buttonsToRemove = [NSMutableArray array];
for (UIView *subview in self.view.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
[buttonsToRemove addObject:subview];
}
}
[buttonsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];
Run Code Online (Sandbox Code Playgroud)
编辑:
我已将我的答案编辑为更好的解决方案。
现在,在枚举数组时,对象不会从数组中删除......
归档时间: |
|
查看次数: |
10447 次 |
最近记录: |