获取验证码需求:封装一个获取验证码的按钮像这样:
- 由于UITextField自身便存在leftView 和rightView,因此本着尽量使用系统自带模块的思路,打算把图片放倒leftView,按钮放在rightView,因此:class InputField: UITextField,并添加图片和按钮,(按钮是一个extention)
let imageView = UIImageView(image: image)
leftViewMode = UITextFieldViewMode.always
rightView = UIButton(60)
rightView?.frame = CGRect(x: 0, y: -10, width: 100, height: 30)
rightView?.layer.cornerRadius = 6
rightView?.layer.masksToBounds = true
rightView = rightView
rightViewMode = UITextFieldViewMode.always
- 但是最终结果却是差强人意,图片的左侧和按钮的右侧紧紧贴着textField的边缘,
为解决这个问题做如下尝试:
- 思路就是ImageView宽度设置宽一点,然后让图片不变形,ok!没有问题
let imageR = image?.size
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: (imageR?.width)! + 20, height: (imageR?.height)!))
imageView.image = image
imageView.contentMode = UIViewContentMode.scaleAspectFit
leftView = imageView
leftViewMode = UITextFieldViewMode.always
- 按钮的话就没有办法了。查过资料之后,发现重写***- (CGRect) rightViewRectForBounds:(CGRect)bounds ***,因此在swift中重写该方法(左视图其实也可以按照这种方式去修改,会比该imageView大小要和规矩的多)
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.rightViewRect(forBounds: bounds)
rect.origin.x += -10
return rect
}
// 一发不可收拾,接着改了后面这些
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.leftViewRect(forBounds: bounds)
rect.origin.x += 10
return rect
}
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
var rect = super.editingRect(forBounds: bounds)
rect.origin.x += 10
rect.size.width -= 20
return rect
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.editingRect(forBounds: bounds)
rect.origin.x += 10
rect.size.width -= 20
return rect
}
最终效果实现,简单功能就没代码了,关键是下面的🕳️!
下面说说坑
-swift3.1 xcode8.3
本来计划不是用继承, 而是打算用***extention UITextField{} ***
但是在重写swift中func rightViewRect(forBounds bounds: CGRect) -> CGRect方法的时候,结果~boom!
报错了method 'rightViewRectForBounds' with Objective-C selector 'rightViewRectForBounds:' conflicts with method 'rightViewRect(forBounds:)' with the same Objective-C selector
查过资料,但是不太明白
- 因为swift和oc重名,所以修改方法名,!修改方法名之后,谁认识他,还重写个J8
- 加private,filePrivate,public 什么的,目的不同但是结果相同,不起作用
如果谁知道解决办法,或者为什么不行,还劳烦通知一下~
按钮是个extention,只是添加了一个方法没有遇到重写的坑,关键代码如下,里面有个dispathSourceTimer,网上资料也是各个版本都有,我的就也贴一下,有问题,找百度
func timeLess() {
var _timeout: Int = tag
let _queue = DispatchQueue.global()
let _timer = DispatchSource.makeTimerSource(queue: _queue)
//创建计时器
_timer.scheduleRepeating(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(_timeout)), interval: DispatchTimeInterval.seconds(1))
_timer.setEventHandler {
//
if _timeout <= 0 {
// 倒计时结束
_timer.cancel()
DispatchQueue.main.async {
// 如需更新UI 代码请写在这里
self.isEnabled = true
self.setTitle("重新获取", for: UIControlState.normal)
self.backgroundColor = UIColor.orange
}
} else {
print(_timeout)
_timeout -= 1
DispatchQueue.main.async {
// 如需更新UI 代码请写在这里
self.setTitle("已发送:\(_timeout)", for: UIControlState.normal)
self.backgroundColor = UIColor.lightGray
}
}
}
_timer.resume()
}
网友评论