无法在故事板上移动自定义 UIView

Can not move custom UIView on storyboard

我已经创建了自定义 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()

}

}

但是当我将它添加到故事板时,无论我把它放在哪里,它都停留在父视图的左上角 as you can see dots shows that view has moved but drawings are out of view and at the left top

问题是什么,如何解决?

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

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

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