簡體   English   中英

如何從超級視圖中獲取所有元素(如:UiLabel,UITextfield)並設置標簽文本顏色和文本字段占位符顏色

[英]How to get all element(Like: UiLabel,UITextfield) from superview and set the label text color and textfield placeholder color

我在設置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循環內,並更改了與UIlabel文本顏色相同的UITextfield占位符顏色

您需要遍歷所有子視圖並檢查相應的類型以更改其屬性。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM