swift 使用UIButton

這是關於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(0, 250, 200, 100)
        //定製按鈕
        let button = UIButton(frame: CGRectMake(10,250,100,50))
        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))
    }

    }

就是這樣了,直接通過初始化方法創建一個按鈕

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章