我尝试从
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);
}
}
请帮忙。
使用此代码:
- (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 的子视图即可。
迅捷解决方案4.0+
func getAllButtonFromViewRecursion(view: UIView) {
for insideView in view.subviews {
if insideView.subviews.count > 0 {
getAllButtonFromView(view: insideView)
}
else if (insideView.isKind(of: UIButton)) {
insideView.layer.borderWidth = 1.0
insideView.layer.borderColor = UIColor.white.cgColor
insideView.layer.cornerRadius = 2.0
}
}
}
目标C解决方案
- (void)getAllButtonFromViewWithRecursion:(UIView*)view {
for (UIView* insideView in view.subviews) {
if (insideView.subviews.count > 0) {
[self getAllButtonFromView:insideView];
}
else if ([insideView isKindOfClass:[UIButton class]]) {
NSLog(@"found a button!");
insideView.layer.borderWidth = 1.0f;
insideView.layer.borderColor = [[UIColor whiteColor] CGColor];
[insideView.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
}
}
环球银行金融电信协会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
}
}
Swift 5。我有 25 个按钮。 1 行 3 个按钮。所有按钮都有不同的尺寸。 1 个 stackView 中的 3 个按钮和 1 个堆栈中的所有行。如何获取所有带有标签的按钮。也许有人帮忙。
for allSubview in self.buttonsStackView.subviews {
for subview in allSubview.subviews {
if subview is UIButton {
switch subview.tag {
case 100...125:
subview.layer.cornerRadius = 20
subview.layer.borderWidth = 1
subview.layer.borderColor = UIColor.white.withAlphaComponent(0.3).cgColor
default:
break
}
}
}
}