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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26050655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:49:06  来源:igfitidea点击:

How to create a circular button in Swift?

iosswiftuibutton

提问by User

I want to make a circular thumbs up and thumbs down button.

我想做一个圆形的拇指向上和拇指向下按钮。

Should I use a ImageView or a Button as the super class?

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

How would I do this in Swift?

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

回答by vacawama

Here is an example round button:

这是一个圆形按钮示例:

Swift 3:

斯威夫特 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:

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