gpt4 book ai didi

swift - CAShapelayer 未显示

转载 作者:行者123 更新时间:2023-11-30 13:40:06 25 4
gpt4 key购买 nike

我一直在尝试向我的 View 和按钮添加一个图层,但不知何故该图层根本没有出现。我错过了什么?

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 中,但图层似乎不可见(也尝试在点击时更改颜色等,设置位置或仅编辑图层本身而不添加新图层)。

最佳答案

您错过了“|”在你的约束字符串中。请更新为,

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com