2014-09-26 26 views

Trả lời

89

Dưới đây là một ví dụ vòng nút:

Swift 3:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let button = UIButton(type: .custom) 
    button.frame = CGRect(x: 160, y: 100, width: 50, height: 50) 
    button.layer.cornerRadius = 0.5 * button.bounds.size.width 
    button.clipsToBounds = true 
    button.setImage(UIImage(named:"thumbsUp.png"), for: .normal) 
    button.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchUpInside) 
    view.addSubview(button) 
} 

func thumbsUpButtonPressed() { 
    print("thumbs up button pressed") 
} 

Swift 2.x:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let button = UIButton(type: .Custom) 
    button.frame = CGRect(x: 160, y: 100, width: 50, height: 50) 
    button.layer.cornerRadius = 0.5 * button.bounds.size.width 
    button.clipsToBounds = true 
    button.setImage(UIImage(named:"thumbsUp.png"), forState: .Normal) 
    button.addTarget(self, action: #selector(thumbsUpButtonPressed), forControlEvents: .TouchUpInside) 
    view.addSubview(button) 
} 

func thumbsUpButtonPressed() { 
    print("thumbs up button pressed") 
} 
+3

Để có được điều này để làm việc tôi đã có thêm ' button.clipsToBounds = true' – Carl

+0

Có cách nào để thực hiện điều này với các ràng buộc không? Tôi không sử dụng mã 'button.frame = CGRect ...'. –

+4

@ArchieGertsman, chắc chắn rồi. Đặt giới hạn tỷ lệ khung hình (chiều rộng == chiều cao) sao cho nút của bạn vuông. Sau đó, chuyển mã 'button.layer.cornerRadius = ...' thành ghi đè 'viewDidLayoutSubviews'. Bạn phải làm điều đó vì bạn cần đảm bảo * Bố cục tự động * đã chạy. – vacawama

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