首页 > 解决方案 > 如何从超级视图中获取所有元素(如:UiLabel,UITextfield)并设置标签文本颜色和文本字段占位符颜色

问题描述

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

在此处输入图像描述

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

这是我用来识别 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 文本颜色相同

标签: iosiphoneswiftuiviewuilabel

解决方案


您需要浏览所有子视图并检查相应的类型以更改其属性。

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
        }
    }

推荐阅读