我有一个带有UIView的自定义类的UIView。我试图在UIView的确切中心绘制一个点,但它出现在稍微偏离中心的底部:
自定义类在这里:
import UIKit
class TimerView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawDot()
}
func drawDot() {
let midViewX = self.frame.midX
let midViewY = self.frame.midY
let dotPath = UIBezierPath(ovalIn: CGRect(x: midViewX, y: midViewY, width: 5, height: 5))
let dotLayer = CAShapeLayer()
dotLayer.path = dotPath.cgPath
dotLayer.strokeColor = UIColor.blue.cgColor
self.layer.addSublayer(dotLayer)
}
}
答案 0 :(得分:1)
这是TimerView
类的重新实现。对于UIView
,init
不是获取frame/bounds
值的最佳位置,因为一旦autolayout
在运行时应用约束,它可能会改变。 layoutSubviews
是为父/子视图获取正确的frame/bounds
值并设置子空间属性的最佳位置。其次,您应该使用父视图bounds
来设置孩子的frame
。
class TimerView: UIView {
private var dotLayer: CAShapeLayer?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
dotLayer = CAShapeLayer()
dotLayer?.strokeColor = UIColor.blue.cgColor
self.layer.addSublayer(dotLayer!)
}
override func layoutSubviews() {
super.layoutSubviews()
drawDot()
}
func drawDot() {
let midViewX = self.bounds.midX
let midViewY = self.bounds.midY
let dotPath = UIBezierPath(ovalIn: CGRect(x: midViewX, y: midViewY, width: 5, height: 5))
dotLayer?.path = dotPath.cgPath
}
}