您的位置:首页 > 移动开发 > Swift

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

2017-04-25 17:46 363 查看
//
//  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)
}
}


调用的时候通过文件类名就可以直接调用了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift class
相关文章推荐