gpt4 book ai didi

swift - NSLayoutConstraint:在 View 之间添加线

转载 作者:行者123 更新时间:2023-11-28 07:56:34 25 4
gpt4 key购买 nike

我面临 NSLayoutConstraint 问题。我以编程方式创建了一个 View ,并想在两个 View 之间添加线条。线条已创建,但它已添加到 View 内部,如图所示: enter image description here

我怎样才能在 View 之间保持这些线条。这是我的代码:

  import UIKit
class ViewController: UIViewController {
@IBOutlet weak var dashBoardView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.dashBoardView.removeFromSuperview()
// Do any additional setup after loading the view, typically from a nib.
var x :Int
var y : Int
x = 0;
y=50;
for i in 0..<5 {
//setting view frame
var view = UIView(frame: CGRect(x: x,y : y,width: 50,height:50))
view.backgroundColor = UIColor.red
self.view.layer.cornerRadius = 5.0
self.view.addSubview(view)
//y for next view should be height of previous view and margin between view
y += 100
//setting the lineView
let pathView = PathView()
pathView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pathView)
NSLayoutConstraint.activate([
pathView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pathView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
pathView.topAnchor.constraint(equalTo: view.topAnchor),
pathView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
pathView.backgroundColor = .clear
let path = UIBezierPath()
path.move(to: CGPoint(x: 10, y:10))
path.addLine(to: CGPoint(x: 100, y: 100))
path.lineWidth = 3
pathView.path = path
}

}

}

这是我的 PathView 类;

import UIKit
class PathView : UIView
{
var path: UIBezierPath?
{ didSet { setNeedsDisplay() } }
var pathColor: UIColor = .blue
{ didSet { setNeedsDisplay() } }

override func draw(_ rect: CGRect) {
// stroke the path
pathColor.setStroke()
path?.stroke()
}
}

我知道添加线条是因为在 View 中添加了那些事件约束。但我很困惑如何将它们添加到 View 之外。任何帮助或建议将不胜感激。

最佳答案

请将您的约束更新为:

NSLayoutConstraint.activate([
pathView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pathView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
pathView.topAnchor.constraint(equalTo: view.bottomAnchor),


pathView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 100.0)
])

关于swift - NSLayoutConstraint:在 View 之间添加线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47881287/

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