这是关于UIButton的使用,将介绍一些button的属性,里面的代码我会把注释全部去掉,你可能连起来看会出错,但是单独看一个一个属性或者方法是没有问题的
import Foundation
import UIKit
class CreateButton: UIButton {
var target:ViewController?
init(target:ViewController) {
super.init(frame:CGRectZero)
self.target? = target
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createButton() ->UIButton {
//有+按钮
let button = UIButton(type:.ContactAdd)
button.frame = CGRectMake(, , , )
//定制按钮
let button = UIButton(frame: CGRectMake(,,,))
button.setTitle("普通按钮", forState: .Normal)
button.setTitle("选中按钮", forState: .Selected)
button.setTitle("高亮按钮", forState: .Highlighted)
button.setTitle("禁用按钮", forState: .Disabled)
//允许点击
button.enabled = true
//文字颜色
button.setTitleColor(UIColor.yellowColor(), forState:.Normal)
//按钮图片
button.setImage(UIImage(named: "price_list_bg"), forState: .Normal)
//禁用按钮不变暗
button.adjustsImageWhenDisabled = false
//点击按钮不变暗
button.adjustsImageWhenHighlighted = false
//背景颜色
button.backgroundColor = UIColor.blueColor()
//背景图片
button.setBackgroundImage(UIImage(named: "price_list_bg"), forState: .Normal)
//点击事件没有点击对像 button.addTarget(self.target,action:Selector("click"),forControlEvents:.TouchUpInside)
//点击事件有点击对象
button.addTarget(self.target,action: Selector("tap:"), forControlEvents: .TouchUpInside)
return button
}
deinit {
print("button结束")
}
}
然后我们看看按钮的使用:
import UIKit
class ViewController: UIViewController,UITextFieldDelegate{
var createText:CreateTextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//按钮
let button = CreateButton.init(target: self).createButton()
createText = CreateTextField.init()
createText?.delegate = self
self.view.addSubview(CreateLabel().createLabel())
self.view.addSubview(button)
self.view.addSubview(createText!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//按钮的点击事件
func click() {
print("按钮被点击了")
}
//按钮的点击事件
func tap(button:UIButton) {
print(button.titleForState(button.state))
}
}
就是这样了,直接通过初始化方法创建一个按钮