如何解决我用 UIBezierPath 和 CAShapeLayer 制作的箭头如何指向 UILabel 的确切中心?
我使用 UIBezierPath 和 CAShapeLayer 绘制了一个矩形视图,箭头指向视图上方的标签。
我希望箭头指向“P”标签的确切中心,iPhone11 模拟器显示我想要的结果。但是,当我在 iPhone8 模拟器上运行时,箭头并不指向标签的中心。
为什么iPhone8模拟器上的箭头指向的标签右边有点偏?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel! //horizontally and vertically aligned
@IBOutlet weak var pointingView: UIView! // leading & trailing constraints: 0,height:200
override func viewDidLoad() {
super.viewDidLoad()
drawPointingView()
}
private func drawPointingView() {
let path = UIBezierPath()
path.move(to: CGPoint(x: 0,y: 0))
path.addLine(to: CGPoint(x: 0,y: pointingView.frame.height))
path.addLine(to: CGPoint(x: pointingView.frame.width,y: 0))
//draw an arrow pointing out to the center cordinate of the label.
path.addLine(to: CGPoint(x: label.center.x + 15,y: 0))
path.addLine(to: CGPoint(x: label.center.x,y: -18))
path.addLine(to: CGPoint(x: label.center.x - 15,y: 0))
path.close()
let shape = CAShapeLayer()
shape.fillColor = UIColor.blue.cgColor
shape.path = path.cgPath
shape.strokeColor = UIColor.lightGray.cgColor
shape.lineWidth = 1
pointingView.layer.addSublayer(shape)
}
}
解决方法
这是因为您要在 viewDidLoad
进行绘图,而 viewDidLoad
为时过早。您所依赖的所有这些值,例如 pointingView.frame.width
,尚不清楚。你必须等到他们知道之后。否则你只会在错误的地方作画(事实上你就是这样)。
这样的事情是布局的结果,所以你必须等到第一次调用 viewDidLayoutSubviews
之后。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。