乞丐版swift placeholder动画

在swift群里发现有人在找这种动画。感觉这种应该可以自己写,不用找别人的吧?于是自己就想试试能不能成功,毕竟菜鸟。下面是动画效果,大家应该都见过的。

placeholder

没错,就是这个简单的效果!由于分辨率的问题,输入框的边框没显示全😂。自己找了一点儿资料,发现不是很复杂。但是自己对于iOS接触的太少,里面的API什么的都不熟悉,属于摸着石头过河。基本的实现方式就是自定义UITextField这个控件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class LabelInput: UITextField {
var placeholderLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
var animationDuration: TimeInterval = 0.35
override func draw(_ rect: CGRect) {
super.draw(rect)
self.addTarget(self, action: #selector(didEditEnd), for: .editingDidEnd)
}
override func drawPlaceholder(in rect: CGRect) {
super.drawPlaceholder(in: rect)
placeholderLabel = UILabel(frame: CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height))
placeholderLabel.text = placeholder
self.placeholder = nil
placeholderLabel.font = UIFont(name: self.font!.fontName, size: self.font!.pointSize)
self.addSubview(placeholderLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: animationDuration, animations: {
self.placeholderLabel.center = CGPoint(x: self.placeholderLabel.center.x, y: -20)
})
}
func didEditEnd(){
if text?.characters.count == 0 {
UIView.animate(withDuration: animationDuration, animations: {
self.placeholderLabel.center = CGPoint(x: self.placeholderLabel.center.x, y: self.frame.size.height/2)
})
}
}
}

这真真是一个乞丐版了。基本思路就是重写drawPlaceholder这个方法。新建一个UILabel替换掉原来真正的placeholder,然后接下来动画改变的其实是这个label。点击输入框的时候改变label的坐标,输入结束的时候判断一下输入框内容,如果是空的就让label回到原来位置。

这个乞丐版只是改了一下y坐标,颜色什么都没关注,动画也没有调试,没有精确计算,只是一个思路而已。写前端的时候喜欢自己写这些控件之类的,我感觉有些简单的东西,自己写比到网上现找别人的要简单。多动手吧😂