无法在情节提要上移动自定义 UIView



我创建了自定义UIView

import UIKit
@IBDesignable
class CategoryIcon: UIView {
let pi:CGFloat = CGFloat(M_PI)
@IBInspectable var circleColor:UIColor = UIColor.green
@IBInspectable var width:CGFloat = 10
@IBInspectable var radius: CGFloat = 20
override func draw(_ rect: CGRect) {
center = CGPoint(x:bounds.width/2 ,y:bounds.height/2)
let path = UIBezierPath(ovalIn: rect)
path.lineWidth = width
circleColor.setStroke()
path.stroke()
}
}

但是当我将其添加到情节提要时,无论我把它放在哪里,它都停留在父视图的左上角,因为您可以看到点显示视图已移动,但绘图不在视图中并且位于左上角

问题是什么,如何解决?

draw(rect:)方法中删除以下行:

center = CGPoint(x:bounds.width/2 ,y:bounds.height/2)

通常不建议在执行绘图代码时更改视图的状态。但在这种特殊情况下,您将根据视图bounds的原点更改视图frame的位置,通常为(0, 0),除非您在其他地方修改了边界。目前尚不清楚您希望通过这样做实现什么,但它实际上所做的是将视图移动到左上角。

最新更新