import Foundation
import UIKit
enum Toast {
static func toast(at view: UIView, message: String, completion: (() -> Void)? = nil) {
let toastLabel = MGSLabel(frame: .zero)
toastLabel.text = " \(message) "
toastLabel.numberOfLines = 0
toastLabel.font = UIFont.systemFont(ofSize: 15.0)
toastLabel.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
toastLabel.textColor = .white
toastLabel.textAlignment = .center
toastLabel.layer.cornerRadius = 7.0
toastLabel.layer.masksToBounds = true
toastLabel.textInsets = UIEdgeInsets(top: 5.0, left: 0, bottom: 5.0, right: 0)
view.addSubview(toastLabel)
toastLabel.setContentHuggingPriority(.init(rawValue: 750.0), for: .horizontal)
toastLabel.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.trailing.equalToSuperview().inset(10.0)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
toastLabel.removeFromSuperview()
completion?()
}
}
}
其中, MGSLabel 的代码为:主要功能:可以设置 UILabel 的上下左右间距
import Foundation
import UIKit
class MGSLabel: UILabel {
var textInsets: UIEdgeInsets = .zero
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insets = textInsets
var rect = super.textRect(forBounds: UIEdgeInsetsInsetRect(bounds, insets),
limitedToNumberOfLines: numberOfLines)
rect.origin.x -= insets.left
rect.origin.y -= insets.top
rect.size.width += (insets.left + insets.right)
rect.size.height += (insets.top + insets.bottom)
return rect
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)