【问题标题】:Find UILabel in UIView in Swift在 Swift 的 UIView 中查找 UILabel
【发布时间】:2014-08-20 19:08:44
【问题描述】:

我试图在我的 UIViewControllers 的超级视图中找到我的 UILabel。 这是我的代码:

func watch(startTime:String, endTime:String) {
    if superview == nil {println("NightWatcher: No viewcontroller specified");return}

    listSubviewsOfView(self.superview!)

}

func listSubviewsOfView(view: UIView) {
    var subviews = view.subviews

    if (subviews.count == 0) { return }

    view.backgroundColor = UIColor.blackColor()

    for subview in subviews {
        if subview.isKindOfClass(UILabel) {
            // do something with label..
        }
        self.listSubviewsOfView(subview as UIView)
    }
}

这是在 Objective-C 中推荐的方式,但在 Swift 中,我只得到 UIViews 和 CALayer。我在提供给此方法的视图中肯定有 UILabels。我错过了什么?

我的 UIViewController 中的调用:

  NightWatcher(view: self.view).watch("21:00", endTime: "08:30") // still working on

【问题讨论】:

  • 我用 Xcode 6b6 对此进行了测试,它工作正常:我能够在 UIView 中找到一个 UILabel,它是我的 viewController 视图的子视图。你使用 Xcode 6b6 吗?你使用故事板吗?您何时/如何调用此方法?
  • 感谢您的回复。我使用 Xcode6b5,故事板。该方法放置在一个单独的非 UI 类中,我从 UIViewController 调用它。
  • watch: 中,当您调用listSubviewsOfView(view) 而不是listSubviewsOfView(self.superview!) 时会得到什么?
  • 我的班级中有一个名为:var superview:UIView? 的变量。我不能称它为“视图”。因此,超级视图是“self.view”

标签: ios swift uiview uilabel


【解决方案1】:

以下版本将在您传入的任何视图中返回所有 UILabel 视图中的 Array

func getLabelsInView(view: UIView) -> [UILabel] {
    var results = [UILabel]()
    for subview in view.subviews as [UIView] {
        if let labelView = subview as? UILabel {
            results += [labelView]
        } else {
            results += getLabelsInView(view: subview)
        }
    }
    return results
}

然后你可以遍历它们来做任何你想做的事情:

override func viewDidLoad() {
    super.viewDidLoad()

    let labels = getLabelsInView(self.view)
    for label in labels {
        println(label.text)
    }
}

【讨论】:

  • 这很好用.. 谢谢!我会试着找出问题所在
  • 我在 Swift 3.1 中运行它,但它返回两个对象,其中一个是 UIButton 的标签,而不是 UILabel 本身。有没有办法让它更明确?
  • @Alexandros 这里也一样。你找到更好的解决方案了吗?
  • 我正在这样做:for case let label as UILabel in view.subviews {...}
【解决方案2】:

使用函数式编程概念,您可以更轻松地实现这一目标。

let labels = self.view.subviews.flatMap { $0 as? UILabel }

for label in labels {
//Do something with label
}

【讨论】:

  • 将此更新为可接受的答案,因为它适用于所有使用 Swift 2.0+ 的代码库。它更干净,(有争议的)更具可读性。斯威夫特已经走了很长一段路:)
  • 我收到Value of type 'UIView' has no member 'flatMap'
  • @Gal 如果您在正确的上下文中编写该代码,它应该可以工作。注释掉这段代码并 cmd+B。你看到任何错误吗?如果没有取消注释并 cmd+B 再次
【解决方案3】:

斯威夫特 4

熟悉 mKane 的答案,您可以使用此代码:

let labels = self.view.subviews.compactMap { $0 as? UILabel }

for label in labels {
   // do whatever
}

【讨论】:

    【解决方案4】:

    您可以在情节提要中将tag 设置为您的UILabel,或以编程方式使用:

    myLabel.tag = 1234 
    

    然后,找到它使用:

    let myLabel = view.viewWithTag(1234)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2015-05-09
      相关资源
      最近更新 更多