小编典典

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

swift

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

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

我将如何在Swift中做到这一点?


阅读 408

收藏
2020-07-07

共1个答案

小编典典

这是一个圆形按钮示例:

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