如何从superview获取所有元素(如:UiLabel,UITextfield)并设置标签文本颜色和文本字段占位符颜色

时间:2018-05-30 06:56:41

标签: ios iphone swift uiview uilabel

我在设置UITextfield占位符颜色和UIlabel文本颜色时遇到问题

enter image description here

  1. 我们可以在给定的屏幕中看到我需要的东西。
  2.   

    以下是我用来识别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)
               }
        }
    
    1. 问题是UITextfield占位符和UIButton文本进入UILabel循环并更改UITextfield占位符颜色与UIlabel文本颜色相同

2 个答案:

答案 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)
            }
        }

    }