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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29888253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:47:23  来源:igfitidea点击:

Change custom text field background color and text color IOS Swift

iosswiftuitextfielddelegate

提问by Arvin Jayanake

I'm using following custom text field class to change appearance of the text field. Now I need to change text field's background color, text color and place holder color, when user start editing and end editing the text field. How to do it, using this 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
    }

}

采纳答案by Yaser

Add self as a target for the UIControl events you need according to documentation

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

There you have control events for EditingDidBegin and such.

在那里你有 EditingDidBegin 等的控制事件。

Something like this:

像这样的东西:

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

回答by Eendje

In your CustomTextFieldclass you can add a property observer:

在您的CustomTextField课程中,您可以添加一个属性观察者:

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

and in your ViewController:

并在您的 ViewController 中:

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

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

Don't forget to set the delegate of your textfield, in storyboard or programmatically.

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

EDIT:
Shortened the code and updated for Swift 3

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

回答by HafizAnser

Select the text field -> click "identity inspector" icon -> click on Plus button "user Defined runtime attributes" -> add this text "_placeholderLabel.textColor" in "key path" field -> choose the "Type" "color" and set the value color.Please check the images in detail

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