如何在Swift 5.1中创建一个圆形计算器按钮?



祝大家一切顺利。

我正在学习iOS开发。我试图构建的第一个应用程序是一个计算器应用程序。我已经开始构建UI并创建按钮。查看下面运行的应用程序的代码和截图。

private func setupNumPad(){
let buttonSize: CGFloat = view.frame.size.width/4

let zeroButton = UIButton(frame: CGRect(x: 0, y: holder.frame.size.height-buttonSize, width: buttonSize*3, height: buttonSize))
zeroButton.setTitle("0", for: .normal)
holder.addSubview(zeroButton)

for x in 0..<3{
let buttonOnetoThree = UIButton(frame: CGRect(x: buttonSize * CGFloat(x), y: holder.frame.size.height-(buttonSize*2), width: buttonSize, height: buttonSize))
buttonOnetoThree.setTitle("(x+1)", for: .normal)
holder.addSubview(buttonOnetoThree)
}

for x in 0..<3{
let buttonFourtoSix = UIButton(frame: CGRect(x: buttonSize * CGFloat(x), y: holder.frame.size.height-(buttonSize*3), width: buttonSize, height: buttonSize))
buttonFourtoSix.setTitle("(x+4)", for: .normal)
holder.addSubview(buttonFourtoSix)
}

for x in 0..<3{
let buttonSeventoNine = UIButton(frame: CGRect(x: buttonSize * CGFloat(x), y: holder.frame.size.height-(buttonSize*4), width: buttonSize, height: buttonSize))
buttonSeventoNine.setTitle("(x+7)", for: .normal)
holder.addSubview(buttonSeventoNine)
}

点击这里查看代码运行图像

然而,如果有人能解释或告诉我如何创建一个圆圈按钮,我会很高兴的。假设我想要的圆圈按钮的背景是白色。任何帮助或指导将不胜感激。

**我没有使用SwiftUI **

for x in 0..<3{
let buttonOnetoThree = UIButton(frame: CGRect(x: buttonSize * CGFloat(x), y: holder.frame.size.height-(buttonSize*2), width: buttonSize, height: buttonSize))
// make circle button
buttonOnetoThree.layer.cornerRadius = buttonSize/2
buttonOnetoThree.backgroundColor = .white
buttonOnetoThree.setTitle("(x+1)", for: .normal)
holder.addSubview(buttonOnetoThree)
}

欢迎来到社区。为了创建一个圆形按钮,你必须改变按钮的layer.corderRadius属性(提示-任何UIView也一样)。为了使它成为一个完美的圆,你必须将cornerRadius设置为宽度或高度的一半(0.5)。以其中一个for-loop为例,您必须进行以下更改:

for x in 0..<3{
let buttonOnetoThree = UIButton(frame: CGRect(x: buttonSize * CGFloat(x), y: holder.frame.size.height-(buttonSize*2), width: buttonSize, height: buttonSize))
buttonOnetoThree.setTitle("(x+1)", for: .normal)
// SETTING THE CORNER RADIUS TO MAKE A CIRCULAR BUTTON -----------------
buttonOnetoThree.layer.cornerRadius = 0.5 * buttonSize // Setting corner radius to half of buttonSize
buttonOnetoThree.clipsToBounds = true // This value makes sure that the view (Button) is within the frame defined
holder.addSubview(buttonOnetoThree)
}

最新更新