我尝试从UIView
获取所有按钮。我试过这段代码,但它没有用。
for (UIView *subview in self.view.subviews)
{
if ([subview isKindOfClass:[UIButton class]]
{
NSLog(@"found a button!");
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
}
请帮忙。
答案 0 :(得分:5)
使用此代码:
- (void)getAllButtonFromView:(UIView*)view {
for (UIView* subview in view.subviews) {
if (subview.subviews.count > 0) {
[self getAllButtonFromView:subview];
}
else if ([subview isKindOfClass:[UIButton class]]) {
NSLog(@"found a button!");
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
}
}
问题可能是您的按钮没有直接添加到视图中,实际上它们会添加到视图的子视图中。因此,只需检查view.subviews中子视图中的视图是否包含包含UIButton的子视图。
答案 1 :(得分:1)
我认为这个片段可以解决您的问题
for (UIView *subview in self.view.subviews)
{
if ([subview isKindOfClass:[UIButton class]])
{
NSLog(@"found a button!");
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
if( [subview isKindOfClass:[UIView class]])
{
for(UIView *furtherView in subview.subviews)
{
if ([furtherView isKindOfClass:[UIButton class]])
{
NSLog(@"found a button!");
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
}
}
}
答案 2 :(得分:0)
SWIFT 5.2
for subview in self.view.subviews {
if subview is UIButton {
let button = subview as! UIButton
// do smth with a button
button.setBackgroundImage(nil, for: .normal)
button.isUserInteractionEnabled = true
}
}