【问题标题】:Increasing the corner radius of UITextField removes its shadow增加 UITextField 的圆角半径会移除它的阴影
【发布时间】:2016-11-18 15:44:10
【问题描述】:

我有一个带有自定义代码的 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
        }
    }

}

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

    当您向UIView 添加圆角半径时,您必须将clipsToBoundsmasksToBounds 设置为true。这不允许创建阴影,因为阴影是在超出边界创建的。

    作为此问题的解决方案,您必须为具有剪角的UIView 创建一个superView,并为此superView 添加一个阴影(确保将超级视图设置为清除颜色)

    【讨论】:

    • 您的代码没有问题。更改layer.masksToBounds = cornerRadius > 0 将删除圆角半径但添加阴影。就像我说的那样,您必须创建一个UIView 并为其添加阴影,然后将要添加角半径的视图添加到其中作为子视图。基本上将cornerRadius 代码和阴影应用到两个单独的视图。
    • 感谢您抽出宝贵时间帮助社区成为一个协作的地方,Rikh。我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 2018-05-27
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多