Change custom text field background color and text

2019-02-12 14:08发布

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
    }

}

3条回答
放荡不羁爱自由
2楼-- · 2019-02-12 14:44

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

There you have control events for EditingDidBegin and such.

Something like this:

self.addTarget(self, action: "myFunc", forControlEvents: UIControlEvents.EditingDidBegin);
查看更多
Juvenile、少年°
3楼-- · 2019-02-12 14:44

In your CustomTextField class you can add a property observer:

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

and in your 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

查看更多
等我变得足够好
4楼-- · 2019-02-12 14:48

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

查看更多
登录 后发表回答