![](/img/trans.png)
[英]Trying to make a square UIButton “morph” into a circle with animateKeyframesWithDuration
[英]Trying to make a UIButton a circle
我目前正在尝试将按钮制作成圆形,这是我的代码:
var raffleButton:UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
button.setTitle("Tap To Enter Raffle!", for: .normal)
button.setTitleColor(UIColor.red, for: .normal)
button.backgroundColor = .white
button.layer.masksToBounds = true
button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160)
button.layer.cornerRadius = button.frame.width/2
return button
}()
然而,当我运行代码时,按钮被毁容,看起来像下面......圆形和足球。
按钮看起来像它而不是一个圆圈有什么原因吗?
您对是否使用自动布局有些困惑。
您已将translatesAutoresizingMaskIntoConstraints
设置为false
,但随后您正试图操纵框架。
如果您添加约束来设置宽度和高度,您将获得更接近您所追求的结果,但您仍需要调整标签或字体以使其适合:
var raffleButton:UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
button.setTitle("Tap To Enter Raffle!!", for: .normal)
button.setTitleColor(UIColor.red, for: .normal)
button.backgroundColor = .white
button.layer.masksToBounds = true
button.heightAnchor.constraint(equalToConstant: 160).isActive = true
button.widthAnchor.constraint(equalToConstant: 160).isActive = true
button.layer.cornerRadius = 80
return button
}()
由于您设置button.translatesAutoresizingMaskIntoConstraints = false
,此代码将不起作用button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160)
。 按钮的大小将在布局过程中改变(不再是 (160, 160))。 因此,它不是一个圆。
您可以更改button.translatesAutoresizingMaskIntoConstraints = false
或尝试在viewDidLayoutSubviews
方法中设置按钮的cornerRadius
。
您的按钮高度与按钮宽度相同,然后设置此代码..
anyButton.backgroundColor = .clear
anyButton.layer.cornerRadius = anyButton.frame.height / 2
anyButton.layer.borderWidth = 1
anyButton.layer.borderColor = UIColor.black.cgColor
需要注意的一件半明显的事情是,如果按钮框架的高度和宽度不相等,则它不会是一个圆圈:)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.