Swift Animate Textfield

时间:2017-06-19 00:57:35

标签: swift xcode

我想为我的UItextfield创建一个动画。为此,我创建了一个UITextField的子类,并将代码存储在那里:

import Foundation  
import UIKit  
class textfieldEdit: UITextField, UITextFieldDelegate {  

    let border = CALayer()  
    let width =  CGFloat(2.0)  

    required init?(coder aDecoder: (NSCoder!)) {  
        super.init(coder: aDecoder)  
        self.delegate=self;  
        border.borderColor = UIColor( red: 216/255, green: 216/255, blue: 216/255, alpha: 100 ).cgColor  

        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)  
        border.borderWidth = width  
        self.layer.addSublayer(border)  
        self.layer.masksToBounds = true  
    }  

    override func draw(_ rect: CGRect) {  
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)  
    }  

    override func awakeFromNib() {  
        super.awakeFromNib()  
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)  
    }  

}  

然而,当有人在文本字段内单击时,我想更新文本字段的边框并使其变为绿色。有没有一种有效的方法来做到这一点?我尝试在我的主视图控制器中有人触摸文本框内部时分配一个函数,但它似乎没有用。

1 个答案:

答案 0 :(得分:2)

我建议不要将这些行为结合起来。相反,添加一个带有“触摸已启用”的UIView,然后在此视图中添加一个触摸侦听器,点击向自定义uitextfield中的便捷方法发送消息,或者直接更改它的外观。

这也适用于UIButton。

出于布局目的,只需使按钮或视图具有与标签相同的边缘约束以及其中心X和Y位置。

不要忘记为自定义文字标签调用“setNeedsDisplay”以强制重绘。

What is the most robust way to force a UIView to redraw?

编辑:如果您只对当前正在编辑UITextfield时更改边框颜色感兴趣,请向其添加一个委托,并在其成为第一响应者(正在编辑)时再次更改外观,并在其重新签名时更改一次第一响应者(停止编辑):

How to know when UITextView became first responder

在此更改边框:

 optional func textViewDidBeginEditing(_ textView: UITextView)

https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618610-textviewdidbeginediting

并在此处恢复正常:

 optional func textViewDidEndEditing(_ textView: UITextView)

https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618628-textviewdidendediting