열거 형 유형의 IBInspectable을 만드는 방법
enum
인터페이스 빌더가 정의한 런타임 속성 이 아닙니다 . 다음은 Interface Builder의 Attributes Inspector에 표시되지 않습니다.
enum StatusShape:Int {
case Rectangle = 0
case Triangle = 1
case Circle = 2
}
@IBInspectable var shape:StatusShape = .Rectangle
설명서 에서 : 부울, 정수 또는 부동 소수점 숫자, 문자열, 지역화 된 문자열, 사각형 등 Interface Builder 정의 런타임 속성에서 지원하는 모든 유형의 클래스 선언, 클래스 확장 또는 범주의 모든 속성에 IBInspectable 속성을 연결할 수 있습니다. , 포인트, 크기, 색상, 범위 및 nil.
Q :enum
Interface Builder의 Attributes Inspector에서 어떻게 볼 수 있습니까?
스위프트 3
@IBInspectable은 var shape:StatusShape = .Rectangle
단순히 Interface Builder에 빈 항목을 생성합니다.
Swift와 Interface Builder 사이 의 다리 역할을하는 어댑터를 사용하십시오 .
shapeAdapter
IB에서 검사 가능 :
// IB: use the adapter
@IBInspectable var shapeAdapter:Int {
get {
return self.shape.rawValue
}
set( shapeIndex) {
self.shape = StatusShape(rawValue: shapeIndex) ?? .Rectangle
}
}
조건부 컴파일 접근 방식 (사용 #if TARGET_INTERFACE_BUILDER
) 과 달리 shape
변수 유형은 대상에 따라 변경되지 않으므로 잠재적으로 shape:NSInteger
대 shape:StatusShape
변형 에 대처하기 위해 추가 소스 코드 변경이 필요할 수 있습니다.
// Programmatically: use the enum
var shape:StatusShape = .Rectangle
완전한 코드
@IBDesignable
class ViewController: UIViewController {
enum StatusShape:Int {
case Rectangle
case Triangle
case Circle
}
// Programmatically: use the enum
var shape:StatusShape = .Rectangle
// IB: use the adapter
@IBInspectable var shapeAdapter:Int {
get {
return self.shape.rawValue
}
set( shapeIndex) {
self.shape = StatusShape(rawValue: shapeIndex) ?? .Rectangle
}
}
}
► GitHub 에서이 솔루션을 찾으십시오 .
int로 검사 가능한 열거 형을 설정하는 대신 문자열로 설정할 수도 있습니다. 드롭 다운만큼 바람직하지는 않지만 적어도이 옵션은 어느 정도의 가독성을 제공합니다.
Swift 전용 옵션 :
// 1. Set up your enum
enum Shape: String {
case Rectangle = "rectangle" // lowercase to make it case-insensitive
case Triangle = "triangle"
case Circle = "circle"
}
// 2. Then set up a stored property, which will be for use in code
var shape = Shape.Rectangle // default shape
// 3. And another stored property which will only be accessible in IB (because the "unavailable" attribute prevents its use in code)
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'shape' instead.")
@IBInspectable var shapeName: String? {
willSet {
// Ensure user enters a valid shape while making it lowercase.
// Ignore input if not valid.
if let newShape = Shape(rawValue: newValue?.lowercased() ?? "") {
shape = newShape
}
}
}
It is possible to also get this to work with objective-c as well, by adding an initializer to the enum. However, the compiler will only show the "unavailable" error for your IB-only properties in swift code.
Swift Option with Obj-C Compatibility:
@objc enum Shape: Int {
case None
case Rectangle
case Triangle
case Circle
init(named shapeName: String) {
switch shapeName.lowercased() {
case "rectangle": self = .Rectangle
case "triangle": self = .Triangle
case "circle": self = .Circle
default: self = .None
}
}
}
var shape = Shape.Rectangle // default shape
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'shape' instead.")
@IBInspectable var shapeName: String? {
willSet {
if let newShape = Shape(rawValue: newValue?.lowercased() ?? "") {
shape = newShape
}
}
}
I can't remember the swift syntax, but this is how I solved it in obj-c
#if TARGET_INTERFACE_BUILDER
@property (nonatomic) IBInspectable NSInteger shape;
#else
@property (nonatomic) StatusShape shape;
#endif
This is an old thread but useful. I have adapted my answer to swift 4.0 and Xcode 9.0 - Swift 4 has its own little issues with this problem. I am having an @IBInspectable variable with enum type and Xcode 9.0 is not happy, showing me this "Property cannot be marked @IBInspectable because its type cannot be representing in Objective-c"
@Eporediese는이 문제 (swift3의 경우)에 부분적으로 답변합니다. 스토리 보드에는 속성을 사용하지만 나머지 코드에는 직선 열거 형을 사용합니다. 다음은 두 경우 모두에서 작업 할 수있는 속성을 제공하는보다 완전한 코드 세트입니다.
enum StatusShape: Int {
case Rectangle = 0
case Triangle = 1
case Circle = 2
}
var _shape:StatusShape = .Rectangle // this is the backing variable
#if TARGET_INTERFACE_BUILDER
@IBInspectable var shape: Int { // using backing variable as a raw int
get { return _shape.rawValue }
set {
if _shape.rawValue != newValue {
_shape.rawValue = newValue
}
}
}
#else
var shape: StatusShape { // using backing variable as a typed enum
get { return _shape }
set {
if _shape != newValue {
_shape = newValue
}
}
}
#endif
SwiftArchitect 기반의 Swift 3 솔루션
enum StatusShape: Int {
case rectangle, triangle, circle
}
var statusShape: StatusShape = .rectangle
#if TARGET_INTERFACE_BUILDER
@IBInspectable var statusShapeIB: Int {
get {
return statusShape.rawValue
}
set {
guard let statusShape = StatusShape(rawValue: newValue) else { return }
self.statusShape = statusShape
}
} //convenience var, enum not inspectable
#endif
I just removed @IBInspectable keyword
//MARK:- Not confirm its will work for other or not but easy way once you can try it
그 오류가 나타난 곳에서 (나에게 두 번). 변경하려면 VHBoomMenuButton 라이브러리의 잠금을 해제해야합니다.
and its work
참고 URL : https://stackoverflow.com/questions/27432736/how-to-create-an-ibinspectable-of-type-enum
'Development Tip' 카테고리의 다른 글
Two-way / bidirectional Dictionary in C#? (0) | 2020.10.21 |
---|---|
Subscribe to observable array for new or removed entry only (0) | 2020.10.21 |
Docker에 SSH를 사용하는 방법은 무엇입니까? (0) | 2020.10.21 |
Visual Studio의 그룹 파일 (0) | 2020.10.21 |
트리거 및 절차로 MySQL 데이터베이스를 내보내는 방법은 무엇입니까? (0) | 2020.10.21 |