在项目开发中经常需要向用户展示一些提示信息,如“请输入...”、“网络...”等提示信息。为方便使用自定义了一个提示View.
该方法旨在供一些短小信息展示使用,文本最多显示两行。
代码如下:
enum AlignmentType:Int {
case center = 0
case bottom
}
final class TipsView: UIView {
static let shared = TipsView()
var textLab:UILabel?
var alignment:AlignmentType = .center
private init() {
super.init(frame: UIScreen.main.bounds)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.alpha = 0.8
self.backgroundColor = UIColor.colorWithHex("5B5B5B")
self.layer.cornerRadius = 3.0
self.textLab = UILabel.init()
self.textLab?.textAlignment = .center
self.textLab?.backgroundColor = UIColor.clear
self.textLab?.textColor = UIColor.white
self.textLab?.font = UIFont.systemFont(ofSize: 13)
self.textLab?.numberOfLines = 2
self.textLab?.sizeToFit()
self.addSubview(self.textLab!)
}
func showTips(info:String) {
self.textLab?.text = info
self.layoutSubviews()
UIApplication.shared.keyWindow?.addSubview(self)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
self.removeFromSuperview()
}
}
func showTips(info:String,alignment:AlignmentType) {
self.textLab?.text = info
self.alignment = alignment
self.layoutSubviews()
UIApplication.shared.keyWindow?.addSubview(self)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
self.removeFromSuperview()
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.frame = CGRect(x: 0, y: 0, width: (self.textLab?.frame.size.width)!+20, height: (self.textLab?.frame.size.height)!)
let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
let attributes:[NSAttributedStringKey:Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):(self.textLab?.font)!,NSAttributedStringKey.paragraphStyle:paragraphStyle.copy()]
let lableSize:CGSize = (self.textLab?.text!.boundingRect(with: CGSize(width: 240, height: 100), options: [.usesLineFragmentOrigin,.usesFontLeading], attributes: attributes, context: nil).size)!
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: lableSize.width+20, height: lableSize.height+20)
if self.alignment == .bottom {
self.center = CGPoint(x: DEVICE_WIDTH/2, y: DEVICE_HEIGHT-150)
} else {
self.center = CGPoint(x: DEVICE_WIDTH/2, y: DEVICE_HEIGHT/2)
}
self.textLab?.frame = self.bounds
}
}
使用方式:
//默认居中显示
TipsView.shared.showTips(info: "收到通知")
//也可以在下方显示
TipsView.shared.showTips(info: "收到通知", alignment: .bottom)