先上效果图:
IMG_0362.PNG
swift版本的提示语,我是完全按照OC的逻辑来编写的,实际上就是换了一种语法而已,相对OC来说,swift更为简洁、易读。
上代码:
import UIKit
class RHToast: UIView {
let ScreentW = UIScreen.main.bounds.width
let ScreentH = UIScreen.main.bounds.height
let KScaleW = UIScreen.main.bounds.width/320.0
let KScaleH = UIScreen.main.bounds.height/568.0
var textLable = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initWithView (view:UIView,text:String,inDuration:CGFloat) ->UIView{
var w = CGFloat(120)
var h = CGFloat(ScreentH-64)
let dic = NSDictionary(object: UIFont.systemFont(ofSize: 14*KScaleW), forKey: NSAttributedString.Key.font as NSCopying)
let size = text.size(withAttributes: dic as? [NSAttributedString.Key : Any])
if size.width > w-20 {
if size.width < 200-20 {
w = size.width + 20
h = size.height + 20
}else{
w = 200
let size1 = text.boundingRect(with:CGSize.init(width: w, height: h), options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any], context: nil)
if size1.height<ScreentH-64-20 {
h = size1.height+20
}
}
}else{
w = size.width + 20
h = size.height + 20
}
self.frame = CGRect(x: (view.bounds.size.width-w)/2, y: (view.bounds.size.height-h)/2, width: w, height: h)
self.layer.cornerRadius = 6
self.alpha = 0
self.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.textLable = UILabel.init(frame: CGRect(x: 10, y: 10, width: self.bounds.size.width-20, height: h-20))
self.textLable.backgroundColor = UIColor.clear
self.textLable.font = UIFont.systemFont(ofSize: 14*KScaleW)
self.textLable.textColor = UIColor.white
self.textLable.numberOfLines = 0
self.textLable.textAlignment = .center
self.textLable.lineBreakMode = .byCharWrapping
self.textLable.text = text
self.addSubview(self.textLable)
view.addSubview(self)
self.show(duration: inDuration)
return self
}
func show(duration:CGFloat) -> Void {
//简单动画
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 1
}, completion: nil)
//定时器
let timer = Timer.scheduledTimer(timeInterval: Double(duration), target: self, selector: #selector(closeToast), userInfo: nil, repeats: false)
RunLoop.current.add(timer, forMode: .common)
}
@objc func closeToast() -> Void {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}) { (true) in
self.removeFromSuperview()
}
}
}
网友评论