2016-11-18 105 views
4

我有一个带自定义代码的UITextField,用于控制圆角半径和占位符颜色以及另一个不同的属性。另外,我有一个扩展协议来从任何UI元素中放置阴影。增加UITextField的圆角半径将消除其阴影

问题是:每当我增加文本字段的圆角半径时,就会丢失阴影。只要角落半径为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 
     } 
    } 

} 

回答

2

当您将角半径添加到UIView您必须将clipsToBoundsmasksToBounds设置为true。这不允许创建阴影时创建阴影外部的界限。

对于这个问题的解决方案,你将不得不创建一个superView到具有被剪切的边角的UIView,并添加阴影,这superView(请务必设置上海华清颜色)

+0

其分毫你的代码不对。更改'layer.masksToBounds = cornerRadius> 0'将移除拐角半径,但添加阴影。 就像我说过的,你将不得不创建一个'UIView'并为它添加一个阴影,并添加一个角度半径的视图作为子视图。基本上应用'cornerRadius'代码并将阴影投影到两个单独的视图。 – Rikh

+0

谢谢你的时间帮助社区成为合作的地方,Rikh。我很感激。 – MEnnabah