Swift 简单易用的弹框提示
这是封装的一个简单,易用,代码比较少的swift弹框提示,能根据文本高度,自行调整位置和弹框高度
//
// ZFSTosatView.swift
// swiftStydy1
//
// Created by HandsomeC on 17/6/15.
// Copyright © 2017年 赵发生. All rights reserved.
//
import UIKit
class ZFSTosatView: UIView {
static func showToast(message:String,fromeSuperView:UIView){
if let label = fromeSuperView.viewWithTag(11111) {//判断是否存在过,每次添加之前删除之前的label
label.removeFromSuperview()
}
let titleLabel = UILabel()
titleLabel.tag = 11111
titleLabel.backgroundColor = UIColor.black
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.textColor = UIColor.white
titleLabel.layer.cornerRadius = 5
titleLabel.layer.masksToBounds = true
titleLabel.numberOfLines = 0
titleLabel.text = message
let stringWidth = ZFSTools.getStringWidth(string: message, font: 15, height: 40)
//只有一行文字的时候
if stringWidth < ZFSTools.SCREENWIDTH() - 30{
titleLabel.frame = CGRect(x:0,y: 0,width: stringWidth+10,height:40)
}else{
//ZFSTools.getStringHeight 和 ZFSTools.SCREENWIDTH()是计算文本高度和屏幕宽度的方法,自行封装
titleLabel.frame = CGRect(x:0,y: 0,width: ZFSTools.SCREENWIDTH() - 30,height:ZFSTools.getStringHeight(string: message, font: 15, width: ZFSTools.SCREENWIDTH() - 30)+10)
}
titleLabel.center = fromeSuperView.center
UIView.animate(withDuration: 0.5, animations: {
fromeSuperView.addSubview(titleLabel)
}, completion: {(b:Bool) -> Void in
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {//弹出以后一秒后自行消失
titleLabel.removeFromSuperview()
}
})
}
}