swift - 无法在 Storyboard上移动自定义 UIView

标签 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()

}

}

但是当我将它添加到 Storyboard 时,无论我把它放在哪里,它都停留在父 View 的左上角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)

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

关于swift - 无法在 Storyboard上移动自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572405/

相关文章:

ios - 搜索 Controller ,圆角不起作用

ios - 标题下方 NavigationBar 上的 UiSegmentedControl

iOS:Interface Builder 中定义的颜色与 Web View 中的颜色不同

SwiftUI:导航到 View 而不获取后退按钮

ios - 两侧带有水平线的 Swift UILabel

swift - Xcode 成功构建但无法运行 macOS 应用程序

objective-c - 在 Mac OS X 应用程序中检测多点触控手势或鼠标拖动

ios - 旋转设备时表格 View 更新无效

arrays - 查找 ScrollView 的索引

ios - 通过 Swift 以编程方式获取 Apple Music 播放列表共享 URL