How to set a max limit for an IBInspectable Int

為{幸葍}努か 提交于 2019-12-30 08:59:43

问题


I am using an IBInspectable Int in Swift to choose between 4 four shapes (0-3), however it is possible in the storyboard editor to set a value greater than 3 and less than 0, which stops the IBDesignable system working.

Is it possible to set a min and max limit of what values can be set in the storyboard editor?

let SHAPE_CROSS = 0
let SHAPE_SQUARE = 1
let SHAPE_CIRCLE = 2
let SHAPE_TRIANGLE = 3

@IBInspectable var shapeType: Int = 0
@IBInspectable var shapeSize: CGFloat = 100.0
@IBInspectable var shapeColor: UIColor?

回答1:


There's no way to limit what a user can input in Storyboard. However, you could prevent invalid values from being stored using a computed property:

  @IBInspectable var shapeType: Int {
    set(newValue) {
      internalShapeType = min(newValue, 3)
    }
    get {
      return internalShapeType
    }
  }

  var internalShapeType: Int = 0

Then you could also use an enum instead of constants to represent your different shape types internally.



来源:https://stackoverflow.com/questions/30831609/how-to-set-a-max-limit-for-an-ibinspectable-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!