我正面临NSLayoutConstraint问题。我以编程方式创建了一个视图,并希望在两个视图之间添加一条线。创建了线,但它被添加到视图中,如图所示:
如何在视图之间保留这些线条。这是我的代码:
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()
}
}
我知道由于视图中添加了这些活动约束而添加了行。但我很困惑,我怎么能在视图外添加它们。任何帮助或建议将真的很感激。
答案 0 :(得分:0)
请更新您的约束:
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)
])