swift中类方法创建button等等其他控件

来源:互联网 发布:数组 push pop 编辑:程序博客网 时间:2024/06/05 03:51
////  QYPButton.swift//  Lease////  Created by Apple on 2017/3/16.//  Copyright © 2017年 Apple. All rights reserved.//import UIKitextension UIButton {    class func createButton(normalTitle:String,selectedTitle:String,frame:CGRect,tag:Int,action:Selector ,target:Any?) -> UIButton {        //1:创建button        let button = UIButton()        //2:设置按钮的bg图片与普通图片        button.frame = frame        button.setTitle(normalTitle, for: .normal)        button.setTitleColor(#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1), for: .normal)        button.setTitle(selectedTitle, for: .selected)        button.setTitleColor(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1), for: .selected)        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)        button.tag = tag        button.addTarget(target, action: action, for: .touchUpInside)        //4:返回按钮        return button    }    class func createButton(image:UIImage,imageSelect:UIImage,tag:Int,action:Selector ,target:Any?) -> UIButton {        //1:创建button        let button = UIButton()        //2:设置按钮的bg图片与普通图片        button.setImage(image, for: .normal)        button.setImage(imageSelect, for: .normal)        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)        button.tag = tag        button.addTarget(target, action: action, for: .touchUpInside)        //4:返回按钮        return button    }    //MARK:-2:提供对象方法:在构造函数的对象方法中,self就是当前调用方法的对象,所以不用再去创建对象    convenience init( _ normalTitle:String,selectedTitle:String,frame:CGRect,tag:Int,action:Selector)   {        //1:必须首先调用self.init()        self.init()        //1:创建button        let button = UIButton()        //2:设置按钮的bg图片与普通图片        button.frame = frame        button.setTitle(normalTitle, for: .normal)        button.setTitleColor(#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1), for: .normal)        button.setTitle(selectedTitle, for: .selected)        button.setTitleColor(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1), for: .selected)        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)        button.tag = tag        button.addTarget(self, action: action, for: .touchUpInside)    }}

调用的时候通过文件类名就可以直接调用了

0 0
原创粉丝点击