我有一个UITextField,其中包含自定义代码来控制角落半径和占位符颜色以及其他不同的属性。同时,我还有一个带扩展协议,用于在任何UI元素中添加阴影。
问题在于:每当我增加文本字段的角半径时,我就会失去阴影。只要角半径为0,我仍然有阴影。
并且,当我增加cornerRadius并失去阴影时,在调试器中会显示出来。
问题在于:每当我增加文本字段的角半径时,我就会失去阴影。只要角半径为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
}
}
}
layer.masksToBounds = cornerRadius > 0
将会删除圆角并添加阴影。就像我所说,你需要创建一个UIView
并向其中添加阴影,然后将要添加圆角的视图作为子视图添加到其中。基本上,将cornerRadius
代码和投影应用于两个不同的视图。 - Rikh