繁体   English   中英

更改自定义文本字段背景颜色和文本颜色 IOS Swift

[英]Change custom text field background color and text color IOS Swift

我正在使用以下自定义文本字段 class 来更改文本字段的外观。 现在,当用户开始编辑和结束编辑文本字段时,我需要更改文本字段的背景颜色、文本颜色和占位符颜色。 如何做到这一点,使用这个 class。

import Foundation
import UIKit

class CustomTextField: UITextField{

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        //Border
        self.layer.cornerRadius = 15.0;
        self.layer.borderWidth = 1.5
        self.layer.borderColor = UIColor.whiteColor().CGColor

        //Background
        self.backgroundColor = UIColor(white: 1, alpha: 0.0)

        //Text
        self.textColor = UIColor.whiteColor()
        self.textAlignment = NSTextAlignment.Center
    }

}

CustomTextField类中,您可以添加属性观察者:

var change: Bool = false {
    didSet {
        textColor = change ? .yellow : .black
        backgroundColor = change ? .blue : .white
    }
}

并在您的ViewController中:

func textFieldDidBeginEditing(textField: UITextField) {
    customTextField.change = true
}

func textFieldDidEndEditing(textField: UITextField) {
    customTextField.change = false
}

不要忘记在故事板中或以编程方式设置文本字段的代理。

编辑:
缩短了代码并更新了Swift 3

根据文档,将self添加为您需要的UIControl事件的目标

你有EditingDidBegin等控制事件。

像这样的东西:

self.addTarget(self, action: "myFunc", forControlEvents: UIControlEvents.EditingDidBegin);

选择文本字段 - >单击“身份检查器”图标 - >单击加号按钮“用户定义的运行时属性” - >在“密钥路径”字段中添加此文本“_placeholderLabel.textColor” - >选择“类型”“颜色”并设置值颜色。 请详细检查图像

@objc func myfunc(_ textfield: UITextField) {

    textfield.backgroundColor = Helper.UIColorFromRGB(0xFFF1F3)
    
}
@objc func myfunc1( _ textfield : UITextField) {
    
    textfield.layer.borderColor = Helper.UIColorFromRGB(0xFF4D67) as! CGColor
    
    textfield.backgroundColor = Helper.UIColorFromRGB(0xFAFAFA)
}


func textfieldBackgroundColor( _ textfield : UITextField) {
    
    textfield.addTarget(self, action: #selector(myfunc), for: UIControl.Event.editingDidBegin)
    textfield.addTarget(self, action: #selector(myfunc1), for: UIControl.Event.editingDidEnd)

    
    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM