swift 3.0+ 工具类

手写UI的同学的福利,看过来
一切都是为了少写代码
有需要的请留言,会奉上Demo

let YV_BC =  RGB(174, G: 153, B: 90)
extension UIButton{
    
    //MARK:  convenience 的初始化方法是不能被子类重写或者是从子类中以 super 的方式被调用的
    /// 创建 UIButton
    ///
    /// - parameter nt:      normal title
    /// - parameter ts:      fontSize,默认 14
    /// - parameter ntc:     normal color,默认 darkGray
    /// - parameter nn:      normal imageNamed
    ///
    /// - returns: UIButton
    convenience init(yv_nt nt: String? = nil,
                     ntc: UIColor? = RGBSingle(176),
                     nn: String? = nil,
                     st: String? = nil,
                     stc: UIColor? = RGBSingle(115),
                     sn: String? = nil,
                     ts: CGFloat? = nil,
                     bts: CGFloat? = nil,
                     rd: CGFloat = 0,
                     bc: UIColor? = nil,
                     bdc: CGColor? = nil,
                     bdw: CGFloat? = 0) {
        self.init()
        if nn != nil {self.setImage(UIImage(named: nn!), for: .normal)}
        self.setTitle(nt, for: .normal)
        self.setTitleColor(ntc, for: .normal)
        
        if sn != nil {self.setImage(UIImage(named: sn!), for: .selected)}
        self.setTitle(st, for: .selected)
        self.setTitleColor(stc, for: .selected)
        if ts != nil {
            self.titleLabel?.font = UIFont.systemFont(ofSize: ts!)
        }
        
        if bts != nil {
            self.titleLabel?.font = UIFont.boldSystemFont(ofSize: bts!)
        }
        
        self.backgroundColor = bc
        self.contentMode = .scaleAspectFill
        self.clipsToBounds = true
        self.layer.cornerRadius = rd
        self.layer.masksToBounds = true
        self.layer.borderColor = bdc
        if bdw != nil {
            self.layer.borderWidth = bdw!
        }
        // 自动调整大小
        sizeToFit()
    }
}
extension UILabel{
    /// 创建 UILabel
    ///
    /// - parameter lt:      text
    /// - parameter ts:  fontSize,默认 14
    /// - parameter ltc:     color,默认 darkGray
    /// - parameter alg: alignment,默认左对齐
    ///
    /// - returns: UILabel
    convenience init(yv_lt lt: String = "labeltitle",
                     ltc: UIColor = UIColor.darkGray,
                     ts: CGFloat? = nil,
                     bts: CGFloat? = nil,
                     alg: NSTextAlignment = .left, isToFit: Bool? = nil) {
        self.init()
        self.text = lt
        self.textColor = ltc
        self.textAlignment = alg
        if ts != nil {
           self.font = UIFont.systemFont(ofSize: ts!)
        }
        if bts != nil {
            self.font = UIFont.boldSystemFont(ofSize: bts!)
        }
        
        if isToFit != nil {
            self.numberOfLines = 0
            // 自动调整大小
            sizeToFit()
        }
    }
}

extension UIImageView{
    convenience init(yv_named named: String,
                     rd: CGFloat = 0,
                     bc: UIColor? = nil,
                     bdc: CGColor? = nil,
                     bdw: CGFloat? = nil) {
        self.init()
        self.image = UIImage(named: named)
        self.backgroundColor = bc
        self.contentMode = .scaleAspectFill
        self.clipsToBounds = true
        self.layer.cornerRadius = rd
        self.layer.masksToBounds = true
        self.layer.borderColor = bdc
        self.layer.borderWidth = bdw == nil ? 0 : bdw!
        self.clipsToBounds = true
        
    }

}


extension UITextField {
    convenience init(yv_pl pl: String = "Placeholder",
                     plc: UIColor = UIColor.red,
                     tc: UIColor = UIColor.darkGray,
                     kt:UIKeyboardType = .default  ,
                     ts: CGFloat = 14,
                     alg: NSTextAlignment = .left,
                     bc: UIColor = RGB(33, G: 176, B: 89),
                     rd: CGFloat = 0){
        self.init()
        
        self.attributedPlaceholder = NSAttributedString(string: pl, attributes: [
            NSForegroundColorAttributeName: plc as Any,
            NSFontAttributeName : UIFont.systemFont(ofSize: ts)
            ])
        self.keyboardType = kt
        self.textAlignment = alg
        self.textColor = tc
        self.backgroundColor = bc
        self.layer.cornerRadius = rd
        self.layer.masksToBounds = true
        
    }
}
extension UITextView {
    convenience init(yv_pl pl: String = "Placeholder",
                     plc: UIColor = UIColor.red,
                     tc: UIColor = UIColor.darkGray,
                     kt:UIKeyboardType = .default  ,
                     ts: CGFloat = 14,
                     alg: NSTextAlignment = .left,
                     bc: UIColor = RGB(33, G: 176, B: 89),
                     rd: CGFloat = 0){
        self.init()
        
        self.text = pl
        self.keyboardType = kt
        self.textAlignment = alg
        self.textColor = tc
        self.backgroundColor = bc
        self.layer.cornerRadius = rd
        self.layer.masksToBounds = true
    }
}

let HomeSubviewHeight = ScreenHeight - 64 - 49

extension UIScrollView {

    convenience init(yv_bc bc: UIColor =  RGB(33, G: 176, B: 89),
                     any: Any,
                     isP: Bool = false,cs: CGSize = CGSize(width: ScreenWidth * 3,height: HomeSubviewHeight)) {
        self.init()
        self.backgroundColor = bc
        self.delegate = any as? UIScrollViewDelegate
        self.isPagingEnabled = isP
        self.scrollsToTop = false
        self.showsHorizontalScrollIndicator = false
        self.showsVerticalScrollIndicator = false
        self.contentSize = cs
        
    }
}
extension UITableView{
    
    convenience init(yv_bc bc: UIColor = RGB(33, G: 176, B: 89),
                     any: Any,
                     rh: CGFloat = 50,tabstyle: UITableViewStyle = .plain,style: UITableViewCellSeparatorStyle = .singleLine) {
        self.init(frame: CGRect.zero, style: tabstyle)
        self.separatorStyle = style
        self.backgroundColor = bc
//        self.tableHeaderView = UIView(frame: CGRect.zero)
        self.rowHeight = rh
        self.delegate = any as? UITableViewDelegate
        self.dataSource = any as? UITableViewDataSource
        
    }
    
}
extension UICollectionView{
    
    convenience init(yv_bc bc: UIColor =  RGB(33, G: 176, B: 89),
                     any: Any,
                     isP: Bool = false,layout: UICollectionViewLayout) {
        
        self.init(frame: CGRect.zero, collectionViewLayout: layout)
        self.backgroundColor = bc
        self.dataSource = any as? UICollectionViewDataSource
        self.delegate = any as? UICollectionViewDelegate
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
        self.isPagingEnabled = isP
        
    }
    
}

extension UICollectionViewFlowLayout{
    
    convenience init(yv_si si: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0),
                     sd: UICollectionViewScrollDirection? = nil,
                     mls: CGFloat = 0,
                     mis: CGFloat = 0,
                     ise: CGSize = CGSize(width: 50, height: 50) ) {
        self.init()
        self.sectionInset = si
        self.scrollDirection = sd == nil ? .horizontal : sd!
        self.minimumLineSpacing = mls
        self.minimumInteritemSpacing = mis
        self.itemSize = ise
    }
}

extension Date {
    /// "yyyy-MM-dd'T'HH:mm:ss"
    static var UTCDate: String {
        get {
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
            return formatter.string(from: date)
        }
    }
    static var UTCDateNo: String {
        get {
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter.string(from: date)
        }
    }
    static var UTCDateZZ: String {
        get {
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
            return formatter.string(from: date)
        }
    }
    static var YearMonth: String {
        get {
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "YYYY/MM"
            return formatter.string(from: date)
        }
    }
    static var MonthDayr: String {
        get {
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "MM/dd"
            return formatter.string(from: date)
        }
    }
    static func dateFromUTCstring(_ utc: String) -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let date = formatter.date(from: utc)
        return date
    }
}
extension UINavigationController {
    //来回push防止底部工具栏出现
    func pushVCHT(_ vc: UIViewController) {
        vc.hidesBottomBarWhenPushed = true
        pushViewController(vc, animated: true)
    }
}
extension UIView {
    convenience init(yv_bc: UIColor? = nil) {
        self.init()
        self.backgroundColor = yv_bc
    }
    func addSubviews(_ views: Array<UIView>) {
        _ = views.map{addSubview($0)}
    }
    func isHiddenSubviews(_ views: Array<UIView>,ishidden: Bool) {
        _ = views.map{$0.isHidden = ishidden}
    }
    
    func yv_viewToImage() -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result!
        
    }
}
extension UIImage {

    //裁剪图片
    func yv_cropImage(rect: CGRect) -> UIImage {
        
        let sourceImageRef = self.cgImage
        let newImageRef = sourceImageRef!.cropping(to: rect)
        
        let newImage = UIImage(cgImage: newImageRef!)
        return newImage
    }
    
    /// 异步绘制图像
    func yv_asyncDrawImage(rect: CGRect,
                           isCorner: Bool = false,
                           backColor: UIColor? = UIColor.white,
                           finished: @escaping (_ image: UIImage)->()) {
        
        // 异步绘制图像,可以在子线程进行,因为没有更新 UI
        
         DispatchQueue.global().async {
            
            // 如果指定了背景颜色,就不透明
            UIGraphicsBeginImageContextWithOptions(rect.size, backColor != nil, 1)
            
            let rect = rect
            
            if backColor != nil{
                // 设置填充颜色
                backColor?.setFill()
                UIRectFill(rect)
            }
            
            // 设置圆角 - 使用路径裁切,注意:写设置裁切路径,再绘制图像
            if isCorner {
                let path = UIBezierPath(ovalIn: rect)
                
                // 添加裁切路径 - 后续的绘制,都会被此路径裁切掉
                path.addClip()
            }
            
            // 绘制图像
            self.draw(in: rect)
            
            let result = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            // 主线程更新 UI,提示:有的时候异步也能更新 UI,但是会非常慢!
            
            DispatchQueue.main.async {
                finished(result!)
            }
        }
    }
}

extension UIView{
   
    func yvDrawStaticCircle() {
        ///绘制静态圆
        let  StaticCayer = CAShapeLayer()
        StaticCayer.lineWidth = 2
        
        StaticCayer.strokeColor = RGBA(58, G: 193, B: 126, A: 1).cgColor
        
        StaticCayer.fillColor =  UIColor.clear.cgColor
        
        let Staticcenter = CGPoint(x: self.frame.size.width/2, y:  self.frame.size.height/2)
        let Staticradius: CGFloat = 15
        let StaticstartA = CGFloat(0)
        let StaticendA = CGFloat(Double.pi/2 * 4)
        
        let Staticpath = UIBezierPath(arcCenter: Staticcenter, radius: Staticradius, startAngle: StaticstartA, endAngle: StaticendA, clockwise: true)
        
        StaticCayer.path = Staticpath.cgPath
        self.layer.addSublayer(StaticCayer)
        
        let DynamicCayer = CAShapeLayer()
        
        //        DynamicCayer.frame = CGRect(x: 0 , y: 0, width: ProgressWH, height: ProgressWH)
        DynamicCayer.lineWidth = 1.5
        
        DynamicCayer.strokeColor = RGBA(58, G: 193, B: 126, A: 1).cgColor
        
        DynamicCayer.fillColor = UIColor.clear.cgColor
        
        let center = CGPoint(x: self.frame.size.width/2, y:  self.frame.size.height/2)
        
        let radius: CGFloat = 15 - 1.5
        let startA = CGFloat(0)
        let endA = CGFloat(Double.pi/2 * 4)
        
        
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startA, endAngle: endA, clockwise: true)
        
        DynamicCayer.path = path.cgPath
        
        self.layer.addSublayer(DynamicCayer)
        DynamicCayer.strokeEnd = 0
        
    }
    func yvDrawDynamicCircle(progress: Float) {
        (self.layer.sublayers?.last as? CAShapeLayer)?.strokeEnd = CGFloat(progress)
    }
}


public extension NSObject{
    
    //获取类名
    public class var nameOfClass: String{
        return NSStringFromClass(self).components(separatedBy: ".").last!
    }
    
    public var nameOfClass: String{
        return NSStringFromClass(type(of: self)).components(separatedBy: ".").last!
    }
}
extension Float{
    //秒-> xx:xx
    func getMMSSFromSS() -> String {
        
        let fl_minute: Float =  self/60
        
        let fl_second: Float = self.truncatingRemainder(dividingBy: 60)
        
        let str_second =  String(format: "%02d", Int(fl_second))
        
        let format_time = "\(Int(fl_minute)):\(str_second)"
        
        return format_time
    }
}

有错请指出,望共同进步

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,194评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,058评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,780评论 0 346
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,388评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,430评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,764评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,907评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,679评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,122评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,459评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,605评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,270评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,867评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,734评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,961评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,297评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,472评论 2 348

推荐阅读更多精彩内容