【发布时间】:2020-10-24 16:18:23
【问题描述】:
我希望我的 swift 代码画一条线,就像 x 轴的位置一样。因此,无论对象显示在何种屏幕尺寸中,这条线都位于屏幕的中心。我下面的代码会生成一条线,但它不考虑设备尺寸。我下面的图片显示了一条黑线,这是我当前的代码生成的,橙色线是所需的输出。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let lineView = UIView(frame: CGRect(x: 0, y: 100, width: 320, height: 1.0))
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.black.cgColor
self.view.addSubview(lineView)
}
}
【问题讨论】:
-
为什么你不继承 UIView 并重写它的 draw() 方法来在你想要的地方画你的线? UIBezierPath 可以绘制各种形状 - 尝试 moveTo() 和 lineTo() 绘制一条线,并研究 UIBezierPath 绘制示例。 developer.apple.com/documentation/uikit/uiview/1622529-drawdeveloper.apple.com/documentation/uikit/drawing
标签: swift uiview constraints center layer