[英]How to get all element(Like: UiLabel,UITextfield) from superview and set the label text color and textfield placeholder color
我在設置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)
}
}
您需要遍歷所有子視圖並檢查相應的類型以更改其屬性。
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
}
}
您應該在其他情況下調用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)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.