这些按钮是圆形还是结节状?

问题描述 投票:0回答:1

也许我的眼睛欺骗了我,但在使用此代码创建类似于iPhone手机应用程序的数字键盘的圆形按钮后:

        for subStack in (mainStackView?.arrangedSubviews)! {

            for thisView in (subStack.subviews) {

                if let button = thisView as? UIButton {


                    button.layer.borderWidth = 2
                    button.layer.borderColor = orangeBorderColor

                    button.frame.size.width = 76
                    button.frame.size.height = 76
                    button.layer.cornerRadius = 0.5 * (button.bounds.size.height)
                    button.layer.masksToBounds = true
//                    button.clipsToBounds = true
                    button.backgroundColor = UIColor.lightGray
                    button.titleLabel?.font = button.titleLabel?.font.withSize(30)
                    button.setTitleColor(.black, for: .normal)
                }
            }
        }

我得到的东西看起来像这样:

enter image description here

我已经尝试过使用clipsToBoundsmaskToBounds,我已经尝试了按钮的.frame及其.bounds属性作为算术的基础,但它们看起来仍然是结节而不是圆形。

有人可以提出一个平滑的建议吗?

谢谢!

编辑

当我添加这个:

                print(button.frame.size as Any)
                print(button.bounds.size as Any)
                print(button.layer.cornerRadius as Any)

我在控制台中得到这个:

(76.0, 76.0)
(76.0, 76.0)
38.0
ios button rounded-corners
1个回答
2
投票

您不能直接设置使用约束布局的视图框架,并且必须使用约束来布置堆栈视图的已排列子视图。那是你的问题。自动布局(稍后)会覆盖您设置框架的尝试,因此您的角半径与按钮的大小不匹配。

创建UIButton的子类。在你的子类中,覆盖layoutSubviews来设置按钮的cornerRadius(并且不要忘记调用super.layoutSubviews)。

© www.soinside.com 2019 - 2024. All rights reserved.