我一直试图在我的视图和按钮中添加一个图层,但是以某种方式根本没有出现该图层。我想念什么?
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
}
}
该按钮被添加到视图中而没有问题,但是该图层的任何内容似乎都不可见(也可以在点击时更改颜色,设置位置或仅编辑图层本身而不添加新图层)。
最佳答案
您错过了“ |”在您的约束字符串中。请更新为
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))
关于swift - CAShapelayer不显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35676930/