我在设置UITextfield占位符颜色和UIlabel文本颜色时遇到问题
以下是我用来识别UILabel和UITextfield的代码。
func processSubviewsNight(of view: UIView) {
for subview in view.subviews {
if subview is UITextField {
if let textField : UITextField = subview as? UITextField {
textField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
textField.backgroundColor = UIColor.appBlueColor()
}
}
if subview is UILabel {
if let label : UILabel = subview as? UILabel {
label.textColor = UIColor.white
}
}
if subview is UIButton {
if let button : UIButton = subview as? UIButton {
button.backgroundColor = UIColor.red
}
}
processSubviewsNight(of: subview)
}
}
答案 0 :(得分:1)
您需要浏览所有子视图并检查相应的类型以更改其属性。
for subview in view.subviews {
if let textField = subview as? UITextFiled {
textFiled.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
textField.backgroundColor = UIColor.appBlueColor()
//set properties
} else if let button = subview as? UIButton {
button.backgroundColor = UIColor.red
//set properties
} else if let label = subview as? UILabel {
label.textColor = UIColor.white
//set properties
}
}
答案 1 :(得分:1)
您应该在其他情况下调用processSubviewsNight(of: subview)
。否则,textfield的子视图将传递给此方法。
func processSubviewsNight(of view: UIView) {
for view in self.view.subviews {
if let lbl = view as? UILabel {
label.textColor = UIColor.white
} else if let textField = view as? UITextField {
textField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
textField.backgroundColor = UIColor.appBlueColor()
} else if let button = view as? UIButton {
button.backgroundColor = UIColor.red
} else{
processSubviewsNight(of: view)
}
}
}