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

标签 ios swift uibutton

<分区>

我想制作一个圆形的竖起大拇指和不竖起大拇指的按钮。

我应该使用 ImageView 还是 Button 作为父类(super class)?

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

最佳答案

这是一个圆形按钮的例子:

swift 3、4、5:

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)
}

@objc 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")
}

关于ios - 如何在 Swift 中创建一个圆形按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050655/

相关文章:

ios - Apple、iOS 13、CryptoKit、Secure Enclave - 在使用私钥之前强制执行生物识别身份验证

ios - Xcode 7 测试版 4 : MKMapKit hangs the app

ios - 如何将 NSData 写入 Swift 中的新文件?

ios - 如何通过 iOS Swift 3 中的交互处理 UICollectionViewCell 中的 UITableView?

ios - UserDefault 保存按钮状态

ios - 如何使用 imageEdgeInsets 更改 UIButton 中图像的 tintColor?

ios - 如何更新游戏中心排行榜中的分数,即使它是较低的游戏中心

ios - 具有多行的 UItextField

ios - 在 iOS 上使用 libPhoneNumber 列出所有国家/地区的代码和调用代码

ios - 以编程方式创建的 UIButton 不可见