如何在Swift中创建一个圆形按钮?

时间:2014-09-26 01:26:12

标签: ios swift uibutton

我想制作一个圆形拇指和拇指向下按钮。

我应该使用ImageView还是Button作为超类?

我如何在Swift中执行此操作?

1 个答案:

答案 0 :(得分:124)

以下是一个圆形按钮示例:

斯威夫特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")
}