xcode 如何检查子视图是否为按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10222141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if subview is button or not
提问by Venkat1282
I am developing an application. In that I get all subviews of UITableViewCell.
我正在开发一个应用程序。因为我得到了 UITableViewCell 的所有子视图。
The code for this one is:
这个的代码是:
(void)listSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
// Return if there are no subviews
if ([subviews count] == 0) return;
for (UIView *subview in subviews) {
NSLog(@"%@", subview);
// List the subviews of subview
[self listSubviewsOfView:subview];
}
}
But my problem is how to find out button from that subviews list. Please tell me how to solve this one.
但我的问题是如何从该子视图列表中找出按钮。请告诉我如何解决这个问题。
回答by Martin Pilch
You can iterate through all subviews like this.
您可以像这样遍历所有子视图。
for (id subview in subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
//do your code
}
}
回答by Sahil Kapoor
Swift
迅速
for subview in view.subviews {
if subview is UIButton {
// this is a button
}
}
回答by Natasha
Check if the subview is a button with is AnyClass
, isKind(of aClass: AnyClass)
or isMember(of aClass: AnyClass) API.
检查子视图是否是带有is AnyClass
,isKind(of aClass: AnyClass)
或 isMember(of aClass: AnyClass) API的按钮。
Using is-
使用是-
for subview in self.view.subviews{
if subview is UIButton{
//do whatever you want
}
}
Using isMember(of:)-
使用 isMember(of:)-
for subview in self.view.subviews{
if subview.isMember(of: UIButton.self){
//do whatever you want
}
}
Using isKind(of:)-
使用 isKind(of:)-
for subview in self.view.subviews{
if subview.isKind(of: UIButton.self){
//do whatever you want
}
}
回答by JScarry
To expand on the 'do your code' part of Martin's answer. Once I got the subview, I wanted to test whether it was the right button and then remove it. I can't check the titleLabel of the button directly by using subview.titleLabel so I assigned the subview to a UIButton and then checked the button's titleLabel.
扩展 Martin 答案的“执行代码”部分。拿到子视图后,我想测试它是否是正确的按钮,然后将其删除。我无法使用 subview.titleLabel 直接检查按钮的 titleLabel,因此我将子视图分配给了 UIButton,然后检查了按钮的 titleLabel。
- (void)removeCheckboxes {
for ( id subview in self.parentView.subviews ) {
if ( [subview isKindOfClass:[UIButton class]] ) {
UIButton *checkboxButton = subview;
if ( [checkboxButton.titleLabel.text isEqualToString:@"checkBoxR1C1"] ) [subview removeFromSuperview];
}
}
}