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

时间:2017-04-23 14:29:43

标签: swift xcode uiview custom-view

我创建了自定义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

问题是什么?如何解决?

1 个答案:

答案 0 :(得分:0)

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

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

在执行绘图代码时,通常不建议更改视图的状态。但在这种特殊情况下,您正在根据frame的来源更改视图的位置bounds,通常为(0,0),除非您已经改变了其他地方的界限。目前还不清楚你希望通过这样做完成什么,但它实际上做的是将视图移动到左上角。