2015-04-05 20 views
19

Tôi đang cố gắng tạo UIView s theo chương trình. Làm thế nào để có được một UIButton với một chức năng hành động trong Swift?Cách tạo UIButton theo lập trình

Các mã sau đây không nhận được bất kỳ hành động:

let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50)) 
btn.backgroundColor = UIColor.greenColor() 
btn.setTitle("Click Me", forState: UIControlState.Normal) 
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 
self.view.addSubview(buttonPuzzle) 

Chức năng chọn sau đây là:

func buttonAction(sender: UIButton!) { 
    var btnsendtag: UIButton = sender 
} 

Trả lời

31

Bạn chỉ thiếu mà UIButton đây là. Để bù đắp cho điều này, hãy thay đổi thuộc tính tag của nó.
Đây là bạn trả lời:

let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50)) 
btn.backgroundColor = UIColor.greenColor() 
btn.setTitle("Click Me", forState: UIControlState.Normal) 
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 
btn.tag = 1    // change tag property 
self.view.addSubview(btn) // add to view as subview 

Swift 3,0

let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50)) 
btn.backgroundColor = UIColor.green 
btn.setTitle(title: "Click Me", for: .normal) 
btn.addTarget(self, action: #selector(buttonAction), forControlEvents: .touchUpInside) 
btn.tag = 1    
self.view.addSubview(btn) 

Dưới đây là một chức năng ví dụ chọn:

func buttonAction(sender: UIButton!) { 
    var btnsendtag: UIButton = sender 
    if btnsendtag.tag == 1 {    
     //do anything here 
    } 
} 
+0

Cảm ơn Nó làm việc với tôi –

+2

Nếu == sender.tag 1 {...} –

1

Bạn phải addSubviewthẻ trên btn.

8

Sử dụng thẻ là giải pháp dễ vỡ. Bạn có một cái nhìn và bạn đang tạo và thêm vào nút để quan điểm đó, bạn chỉ cần giữ một tham chiếu đến nó: Ví dụ

Trong lớp học của bạn, giữ một tham chiếu đến nút

var customButton: UIButton! 

Tạo nút và thiết lập các tài liệu tham khảo

let btn = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50)) 
btn.backgroundColor = .greenColor() 
btn.setTitle("Click Me", forState: .Normal) 
btn.addTarget(self, action: #selector(MyClass.buttonAction), forControlEvents: .TouchUpInside) 
self.view.addSubview(btn) 
customButton = btn 

thử nghiệm chống lại trường hợp này trong hàm hành động

func buttonAction(sender: UIButton!) { 
    guard sender == customButton else { return } 

    // Do anything you actually want to do here 
} 
+1

Rất nhỏ, nhưng bạn quên không gian sau khi 'btn' và trước khi '=' đây: 'hãy btn = UIButton. ..' – damianesteban

+0

Cảm ơn, đã được khắc phục ngay bây giờ. – Abizern

Các vấn đề liên quan