检查UIButton的对象类型

时间:2018-06-24 20:22:18

标签: swift

如何验证对象类型?

目标是检查对象自定义类型以检查值

@IBAction func showAnswer(_ sender: UIButton) {
        let question: Question = questions[currentQuestionIndex]
        let rightAnswer = question.answers![question.answer]
        let subViews = self.view.subviews

        subViews.forEach { view in
            if view.isMember(of: AnswerButton.self) {
                let btn = view as! AnswerButton
                if btn.titleLabel!.text == rightAnswer {
                    btn.hightlight()
                }
            }
        }

    }

这是UI。如果答案正确,则带有正确答案的按钮应突出显示。

enter image description here

1 个答案:

答案 0 :(得分:2)

代替

if view.isMember(of: AnswerButton.self) {
  let btn = view as! AnswerButton
  if btn.titleLabel!.text == rightAnswer {
    btn.hightlight()
  }
}

使用conditional downcasting

if let btn = view as? AnswerButton {
  // btn could be accessed as an instance of `AnswerButton` now
  if btn.titleLabel!.text == rightAnswer {
    btn.hightlight()
  }
}

如果不需要向下转换按钮,则可以使用以下条件循环遍历子视图:

for view in subviews where view is AnswerButton {
  // view is still treated as an instance of UIView but could be downcast to AnswerButton
}