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

//
//  QYPButton.swift
//  Lease
//
//  Created by Apple on 2017/3/16.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

extension 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)
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值