2016-02-27 73 views
0

我一直在試圖添加一個圖層到我的視圖和按鈕,但不知何故圖層根本沒有出現。我錯過了什麼?CAShapelayer沒有顯示

class ViewController: UIViewController { 

    var button1: CustomButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     button1 = CustomButton(frame: CGRectZero) 

     let views1 = ["button1": button1] 

     button1.backgroundColor = .clearColor() 
     view.addSubview(button1) 

     view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button1(50)]", options: [], metrics: nil, views: views1)) 
     view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[button1(50)]-50-|", options: [], metrics: nil, views: views1)) 
    } 
} 

class CustomButton: UIButton { 

    let shape = CAShapeLayer() 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     translatesAutoresizingMaskIntoConstraints = false 

     shape.fillColor = UIColor.redColor().CGColor 
     shape.strokeColor = UIColor.blackColor().CGColor 
     shape.lineWidth = 0.5 

     shape.bounds = CGRect(x: 0, y: 0, width: 50, height: 50) 

     layer.insertSublayer(shape, atIndex: 0) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     let padding: CGFloat = 10 

     let x = frame.origin.x - padding 
     let y = frame.origin.y - padding 
     let widths = bounds.width + 2 * padding 
     let height = bounds.height + 2 * padding 

     let rect = CGRect(x: x, y: y, width: widths, height: height) 

     shape.frame = rect 
     shape.path = UIBezierPath(rect: rect).CGPath 
    } 
} 

按鈕添加到視圖沒有問題,但沒有該層似乎可見(一直在努力挖掘等,以及時改變顏色,設置位置,添加或不添加一個新的只需編輯層本身) 。

回答

0

您錯過了'|'在你的約束字符串中。請更新爲,

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button1(50)]|", options: [], metrics: nil, views: views1)) 
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button1(50)]-50-|", options: [], metrics: nil, views: views1))