应用圆角边框以及阴影对UITextField不起作用

时间:2017-05-20 12:43:30

标签: ios swift swift3 uitextfield

我想实现以下用户界面 enter image description here

这是我的代码

class RoundTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        customize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customize()
    }

    func customize() {
        apply(shadow: true)
    }

    func apply(shadow: Bool) {
        if shadow {
            borderStyle = .none
            layer.cornerRadius = bounds.height / 2

            layer.borderWidth = 1.0
            layer.borderColor = UIColor.lightGray.cgColor
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 5.0)
            layer.shadowRadius = 2
            layer.masksToBounds = false
            layer.shadowOpacity = 1.0
        } else {

        }
    }
}

这是问题细节,

  • 案例1:对于上面的代码,我得到一个没有任何边框或阴影的textField,
  • 案例2:如果我评论前两行,我会得到阴影效果,边框不会倒圆,边框会变为默认的圆角边框。
borderStyle = .none
layer.cornerRadius = bounds.height / 2


我怎么能解决这个问题?

3 个答案:

答案 0 :(得分:1)

您应将 layer.masksToBounds 设置为true。

答案 1 :(得分:1)

我无法重现您遇到的案例1,因此我会发布似乎可以实现您想要的UI的代码。

class RoundTextField: UITextField {

    override func layoutSubviews() {
        super.layoutSubviews()
        borderStyle = .none
        layer.cornerRadius = bounds.height / 2
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.init(colorLiteralRed: 241/256, green: 241/256, blue: 241/256, alpha: 1).cgColor
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2
        layer.masksToBounds = false
        layer.shadowOpacity = 1.0
        // set backgroundColor in order to cover the shadow inside the bounds
        layer.backgroundColor = UIColor.white.cgColor
    }
}

这是我模拟器的截图: enter image description here 我还将full project上传到了Dropbox。

答案 2 :(得分:0)

尝试从LayoutSubViews调用这些方法。

override func layoutSubviews() {
        super.layoutSubviews()
        // Call here
    }