我有一个带有自定义代码的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
}
}
}
答案 0 :(得分:2)
向UIView
添加转角半径时,您必须将clipsToBounds
或masksToBounds
设置为true。当阴影在外部边界创建时,这不允许创建阴影。
作为此问题的解决方案,您必须为superView
创建一个具有剪裁角落的UIView
,并为此superView
添加阴影(请务必设置超视图以清除颜色)