2016-09-21 21 views
2

當我使用「用戶定義的運行屬性」時,我很難得到投影陰影。使用用戶定義的運行屬性的UIView陰影

它似乎工作完全正常,如果我使用代碼,如下所示。

func formatView(view: UIView, cornerRadius: Bool) { 

    if (cornerRadius) {view.layer.cornerRadius = 12 } 
    view.layer.shadowColor = UIColor.black.cgColor 
    view.layer.shadowOffset = CGSize.zero 
    view.layer.shadowRadius = 3 
    view.layer.shadowOpacity = 0.3 
} 

但是,當我用用戶定義的運行時屬性嘗試它時,它不再顯示。這些是我目前使用的。

enter image description here

這是奇怪的唯一的事情是,如果我刪除layer.shadowColor屬性,那麼它似乎再工作。但我無法再控制顏色。它似乎默認爲黑色,但如果我決定選擇灰色,我將無法改變它。

這是因爲顏色屬性是一個UIColor和shadowColor期望一個CGColor?

+0

注意的是有點混亂,對於一個UILabel的 「.shadowColor」 的確只是一個的UIColor(!!!!!!!!!!),這樣你就可以只使用udra! – Fattie

回答

5

確實如您所述,因爲用戶定義的運行屬性面板中的Color類型創建了UIColor,但layer.borderColor保留了cgColor類型。

extension CALayer { 
    var borderUIColor: UIColor { 
     set { 
      self.borderColor = newValue.cgColor 
     } 

     get { 
      return UIColor(cgColor: self.borderColor!) 
     } 
    } 
} 

但好得多的辦法是使用IBDesignable的代替用戶自定義運行屬性

你可以通過創建一個類,允許代理的顏色,通過界面生成器設置解決了這個,這更清楚。

您可以通過在項目中添加一個名爲UIViewExtentions.swift一個新的快捷文件做到這一點(或只是粘貼在任何文件):

import UIKit 

@IBDesignable extension UIView { 
    @IBInspectable var borderColor:UIColor? { 
     set { 
      layer.borderColor = newValue!.cgColor 
     } 
     get { 
      if let color = layer.borderColor { 
       return UIColor(cgColor:color) 
      } 
      else { 
       return nil 
      } 
     } 
    } 
    @IBInspectable var borderWidth:CGFloat { 
     set { 
      layer.borderWidth = newValue 
     } 
     get { 
      return layer.borderWidth 
     } 
    } 
    @IBInspectable var cornerRadius:CGFloat { 
     set { 
      layer.cornerRadius = newValue 
      clipsToBounds = newValue > 0 
     } 
     get { 
      return layer.cornerRadius 
     } 
    } 
} 

那麼這將在Interface Builder中的每一個按鈕,ImageView的,標籤等實用工具面板>屬性檢查器:

enter image description here

現在,如果你在屬性檢查器中設置你的價值觀和回頭看看用戶自定義屬性運行時,你會看到他們是部門自動化cally爲你提出!

編輯: 有關詳細信息,請參見:http://nshipster.com/ibinspectable-ibdesignable/

+1

我只想評論一下,這對我來說非常合適。而且我對將來可以使用它的可能性感到興奮。你也幫助我最終了解擴展的力量。但有一個問題,我的更改是否應該在main.storyboard中生效,或者僅在我運行該應用程序時才生效。目前我看到他們在跑步,而不是在故事板上。 –

+1

我很高興能夠提供幫助:)現在,當您擴展現有的控件時,屬性不會實時呈現,而只會在您運行應用程序時呈現。目前,@IBDesignable和@IBInspectable實時渲染僅支持使用類class CustomButton的自定義控件:UIButton @IBInspectable var highlightedBackgroundColor:UIColor? { } }' –