2016-11-18 58 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