如何在Swift 3.0中迭代屏幕上的所有UIButtons?

时间:2016-11-06 16:56:19

标签: ios swift3

我正在尝试循环迭代视图中找到的所有UIButton,以便更改每个按钮的位置。 (见下面的代码)

        for case let button as UIButton in self.view.subviews {
             rect = button.frame
             rect.origin.x = rect.origin.x + 20
             rect.origin.y = rect.origin.y + 20
             button.frame = rect
        }

然而,当我调试代码时,我发现循环没有找到任何按钮,因此位置保持不变。我在View Controller中的View中有9个按钮。

有人知道这个循环有什么问题吗?

2 个答案:

答案 0 :(得分:3)

您的代码适用于我。这意味着您的按钮是{em>不是 self.view的子视图,而是在层次结构中的某些视图的子视图。你必须编写循环的递归版本。

例如:

func lookForButton(_ v: UIView) {
    let subs = v.subviews
    if subs.count == 0 {return}
    for vv in subs {
        if vv is UIButton {
            print(vv) // just testing: do your real stuff here
        }
        lookForButton(vv)
    }
}
lookForButton(self.view)

答案 1 :(得分:0)

您的代码正常运行。这样:

<UIButton: 0x7fcc9bd07320; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x60000002dca0>>

打印:

UIButtons

结论:self.view.subviews不包含任何public ActionResult Index(FeedEventCommand command) { var feedEventViewModel = new FeedEventViewModel { AnimalId = command.AnimalId, AnimalName = command.AnimalName, FeederTypeId = command.FeederTypeId, FeederType = command.FeederType }; feedEventViewModel = new List<feedEventViewModel>(); <--Error line return View(feedEventViewModel); }