最近做项目竟然遇见了和这个差不多的需求,但是更全面,我根据这个的写法做了一个输入框,自我感觉良好,更新在这里,下面是效果图。
pwdField.gif
下载链接:https://pan.baidu.com/s/1n2yYS98sZ7xV99YjrtbFZQ
-------------------------割一下------------------------
这个实在网上看到的。
输入框是比较常用的,特别注册登录,填写信息什么的
我们都知道输入框有个属性placeholder相当于对输入有一个提示作用但是已输入就不见了,有的时候输入一半忘记输入提示是什么了。(记性不好的悲哀),也有些在上面设计一个提示一直存在这样看着页面有不简洁。
最近看到个设计在输入的时候把placeholder变小在输入框上面显示,觉得很好很实用。想这样
Untitled.gif
这样设计上可以留出上面提示的内容简介明了
做法很简单,自定义一个View,上面放上一个textField和一个label,然后根据textField当前的文字来判断label出现和消失。非常简单就不说代码了。直接放在下面给和我一样懒的人拷贝吧。嘿嘿
import UIKit
class SweetTextField: UIView, UITextFieldDelegate {
var textStr:NSString {
get{
return NSString(string: textField.text!)
}
}
var placeHolderStr:String {
set{
textField.placeholder = newValue as String
showView.text = newValue as String
}
get{
return self.placeHolderStr
}
}
private let textField = UITextField()
private let showView = UITextField()
override init(frame: CGRect) {
super.init(frame: frame)
textField.frame = CGRect(x: 0, y: 0.2*bounds.height, width: bounds.width, height: 0.8*bounds.height)
textField.delegate = self
textField.textColor = UIColor.black
textField.font = UIFont.systemFont(ofSize: 15.0)
textField.addTarget(self, action: #selector(textFieldDidChangeText(textField:)), for: UIControlEvents.editingChanged)
self.addSubview(textField)
showView.frame = CGRect(x: 0, y: 0.2*bounds.height, width: bounds.width, height: 0.2*bounds.height)
showView.isUserInteractionEnabled = false
showView.textColor = UIColor.blue
showView.font = UIFont.systemFont(ofSize: 9.0)
showView.alpha = 0.0
self.addSubview(showView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: UITextFieldDelegate
func textFieldDidChangeText(textField:UITextField) {
let text = NSString(string: textField.text!)
if text.length > 0 {
showShowView()
}else{
removeShowView()
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.showView.textColor = UIColor.blue
return true
}
func textFieldDidBeginEditing(_ textField: UITextField){
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool{
return true
}
func textFieldDidEndEditing(_ textField: UITextField){
let text = NSString(string: textField.text!)
if (text.length > 0) {
self.showView.textColor = UIColor.darkGray
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//MARK: CUSTEMMETHODS
func removeShowView() {
UIView.animate(withDuration: 0.5, animations: {
self.showView.alpha = 0.0
self.showView.frame = CGRect(x: 0, y: 0.2 * self.bounds.height, width: self.bounds.width, height: 0.2 * self.bounds.height)
}, completion: { (End) in
self.showView.textColor = UIColor.blue
})
}
func showShowView() {
UIView.animate(withDuration: 0.2) {
self.showView.alpha = 1.0
self.showView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 0.2 * self.bounds.height)
}
}
}
网友评论