模仿Android toast 写的 Swift 版Toast,支持自动换行。
//
// Created by 谭尧 on 2021/7/20.
//
import Foundation
import UIKit
class Toast {
private static var INSTANCE:Toast? = nil
public static func makeText(_ text:String)->Toast{
if INSTANCE == nil {
INSTANCE = Toast()
}
INSTANCE!.toastText = text
return INSTANCE!
}
private let window = UIApplication.shared.windows.first!
private let contentView = UIView()
private let lableToast = UILabel(frame: CGRect(x: 0, y: 0, width: 240, height: 40))
private var toastText = ""
private init(){
lableToast.text = ""
lableToast.textAlignment = .center
lableToast.textColor = .black
lableToast.backgroundColor = .clear
lableToast.numberOfLines = 0
contentView.frame = lableToast.frame
contentView.backgroundColor = .white
contentView.layer.cornerRadius = 12
contentView.layer.borderColor = UIColor.lightGray.cgColor
contentView.layer.borderWidth = 1
contentView.center = CGPoint(x: window.center.x, y: window.center.y*7/5)
contentView.addSubview(lableToast)
}
private var timer:DispatchSourceTimer? = nil
func show(showTimeSec:Int = 3){
if timer != nil {
hide()
}
var w = CGFloat(16)*1.2 * CGFloat(toastText.count), h = CGFloat(40)
if w > 240 {
w = 240
h = 70
}
lableToast.frame.size = CGSize(width: w, height: h)
contentView.frame.size = lableToast.frame.size
contentView.center.x = window.center.x
lableToast.text = toastText
contentView.alpha = 0.0
window.addSubview(contentView)
easyIn()
timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.main)
timer?.schedule(deadline: .now() + .seconds(showTimeSec))
timer?.setEventHandler(handler: {
self.hide()
})
timer?.resume()
}
@objc private func hide(){
self.contentView.removeFromSuperview()
self.timer?.cancel()
self.timer = nil
}
private func easyIn(){
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationCurve(.easeIn)
UIView.setAnimationDuration(0.2)
contentView.alpha = 1.0
UIView.commitAnimations()
}
}
原文地址:https://blog.csdn.net/tanyaobook/article/details/122410750
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_11143.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。