如何在 iPhone/iOS 中在 UIView 下繪製陰影?


為了使我們的使用者介面更具吸引力,我們必須在 iOS 開發中嘗試多種屬性。要在檢視周圍或檢視下方繪製陰影,我們必須試驗圖層和檢視。

讓我們透過兩種方式來實現這一點。

方法 1 − 只需在任何需要的地方進行編碼。

self.layer.masksToBounds = NO;
self.layer.cornerRadius = 2;
self.layer.shadowOffset = CGSizeMake(-5, 10);
self.layer.shadowRadius = 3;
self.layer.shadowOpacity = 0.3;

方法 2 − 建立 IBDesignable 和 IBInspectable,並與故事面板一起使用。

@IBDesignable
class DesignableView: UIView { }
extension UIView {
   @IBInspectable
   var shadowRadius: CGFloat {
      get {
         return layer.shadowRadius
      }
      set {
         layer.shadowRadius = newValue
      }
   }
   @IBInspectable
   var shadowOpacity: Float {
      get {
         return layer.shadowOpacity
      }
      set {
         layer.shadowOpacity = newValue
      }
   }
   @IBInspectable
   var shadowOffset: CGSize {
      get {
         return layer.shadowOffset
      }
      set {
         layer.shadowOffset = newValue
      }
   }
   @IBInspectable
   var shadowColor: UIColor? {
      get {
         if let color = layer.shadowColor {
            return UIColor(cgColor: color)
         }
         return nil
      }
      set {
         if let color = newValue {
            layer.shadowColor = color.cgColor
         } else {
            layer.shadowColor = nil
         }
      }
   }
}

我們可以使用上面針對 UIView 的擴充套件,使所有故事面板都可以訪問這些屬性,並在無需執行就能在裝置上看到結果的情況下嘗試各種設計。這些更改將在故事面板上即時進行。下面是一個示例。

更新於: 27-6 月-2020

180 次瀏覽

提升你的 事業

透過完成課程獲得認證

開始
廣告