2017-09-20 140 views
0

我試圖創建使用IBDesignable下面這個tutorial梯度自定義選項,但我得到意想不到的錯誤,甚至只是從教程應對代碼構建時的錯誤作出梯度

進口的UIKit

@IBDesignable 
class GradientView: UIView { 

    @IBInspectable var FirstColor: UIColor.clear{ 
     didSet { 
      updateView() 
     } 
    } 
    @IBInspectable var SecondColor: UIColor.clear{ 
     didSet { 
      updateView() 
     } 
    } 

    @IBInspectable var ThirdColor: UIColor.clear{ 
     didSet { 
      updateView() 
     } 
     func updateView() { 

     } 
    } 
} 

enter image description here

回答

0

應該是這樣的:

import UIKit 

@IBDesignable 
class GradientView: UIView { 
    @IBInspectable var FirstColor: UIColor = .clear { 
     didSet { 
      updateView() 
     } 
    } 

    @IBInspectable var SecondColor: UIColor = .clear { 
     didSet { 
      updateView() 
     } 
    } 

    @IBInspectable var ThirdColor: UIColor = .clear { 
     didSet { 
      updateView() 
     } 
    } 

    func updateView() { 

    } 
} 
0

嘗試這個

import UIKit 

@IBDesignable class GradientView: UIView { 

    @IBInspectable var topColor: UIColor = UIColor.white { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var bottomColor: UIColor = UIColor.black { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var shadowColor: UIColor = UIColor.black { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var shadowX: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var shadowY: CGFloat = -3 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var shadowBlur: CGFloat = 3 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var startPointX: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var startPointY: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var endPointX: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var endPointY: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    @IBInspectable var cornerRadius: CGFloat = 0 { 
     didSet { 
      setNeedsLayout() 
     } 
    } 

    override class var layerClass: AnyClass { 
     return CAGradientLayer.self 
    } 

    override func layoutSubviews() { 
     let gradientLayer = layer as! CAGradientLayer 
     gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor] 
     gradientLayer.startPoint = CGPoint(x: startPointX, y: startPointY) 
     gradientLayer.endPoint = CGPoint(x: endPointX, y: endPointY) 
     layer.cornerRadius = cornerRadius 
     layer.shadowColor = shadowColor.cgColor 
     layer.shadowOffset = CGSize(width: shadowX, height: shadowY) 
     layer.shadowRadius = shadowBlur 
     layer.shadowOpacity = 1 
    } 
}