增加UITextField的圆角半径会使其阴影消失。

5
我有一个UITextField,其中包含自定义代码来控制角落半径和占位符颜色以及其他不同的属性。同时,我还有一个带扩展协议,用于在任何UI元素中添加阴影。
问题在于:每当我增加文本字段的角半径时,我就会失去阴影。只要角半径为0,我仍然有阴影。
并且,当我增加cornerRadius并失去阴影时,在调试器中会显示出来。
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key height

这是我实现阴影效果的协议:

import UIKit

protocol DropShadow {}

extension DropShadow where Self: UIView {

    func addDropShadow() {
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.7
        layer.shadowOffset = CGSize(width: 0, height: 4)
        layer.shadowRadius = 3
    }
}

这是我的UITextField自定义类:

import UIKit

@IBDesignable
class FancyTextField: UITextField, DropShadow {

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor: UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var placeHolderColor: UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName: placeHolderColor!])
            attributedPlaceholder = str
        }
    }

}
1个回答

2
当您给一个UIView添加圆角时,您必须将clipsToBoundsmasksToBounds设置为true。这样做会防止阴影的创建,因为阴影是在边界外部创建的。
解决此问题的方法是,您需要为具有剪切角的UIView创建一个superView,并将阴影添加到该superView(请确保将superview设置为透明颜色)。

你的代码没有问题。更改 layer.masksToBounds = cornerRadius > 0 将会删除圆角并添加阴影。就像我所说,你需要创建一个 UIView 并向其中添加阴影,然后将要添加圆角的视图作为子视图添加到其中。基本上,将 cornerRadius 代码和投影应用于两个不同的视图。 - Rikh
感谢你花时间帮助社区成为一个协作的地方,Rikh。我非常感激。 - Ennabah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接