2017-10-09 4 views
2

스위프트 3에서 스위프트 4로 이동 중입니다. 라벨에 매우 특정한 텍스트 속성을 부여하는 UILabels가 있습니다. strokeTextAttributes가 초기화 될 때 '선택 값을 언 래핑하는 동안 예기치 않게 발견 된 없음'오류가 발생합니다. 솔직히 말하면 나는 완전히 잃어버린다.스위프트 4 라벨 속성

swift 3의 strokeTextAttributes는 [String : Any] 였지만 신속한 4 번 오류는 내가 아래에있는 것으로 변경하기 전까지 던졌습니다.

let strokeTextAttributes = [ 
    NSAttributedStringKey.strokeColor.rawValue : UIColor.black, 
    NSAttributedStringKey.foregroundColor : UIColor.white, 
    NSAttributedStringKey.strokeWidth : -2.0, 
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18) 
    ] as! [NSAttributedStringKey : Any] 


chevronRightLabel.attributedText = NSMutableAttributedString(string: "0", attributes: strokeTextAttributes) 
+3

'NSAttributedStringKey.strokeColor.rawValue' => 'NSAttributedStringKey.strokeColor'을 대신? – Larme

+0

스위프트는 절대적으로 악몽이며 일반적으로 프로그래밍을위한 중요한 단계입니다. – RunLoop

답변

8

@.rawValue에 대한 @ Larme의 코멘트가 정확하지 않습니다. 또한,이 반복 NSAttributedStringKey.를 제거한다

let strokeTextAttributes: [NSAttributedStringKey: Any] = [ 
    .strokeColor : UIColor.black, 
    .foregroundColor : UIColor.white, 
    .strokeWidth : -2.0, 
    .font : UIFont.boldSystemFont(ofSize: 18) 
] 

:

또한, 명시 적 입력을 사용하여 코드를 충돌 힘 캐스트를 방지 할 수 있습니다.

+0

그리고 dic을 사용하고 동시에 범위를 지정하려면이를 수행 할 수있는 방법이 있습니까? – Neko

+0

[NSAttributedStringKey] (https://developer.apple.com/documentation/foundation/nsattributedstringkey)의 'static let'을 사용할 수 있으므로 범위를 지원하지 않습니다. – XML

0

스위프트 4는 해결책 자체를 제안합니다. Swift 4.0에서 특성 문자열은 키 유형이 NSAttributedStringKey 인 json (사전)을 허용합니다. 그래서 당신은 스위프트 4.0 AttributedString에 대한 [NSAttributedStringKey : Any]

Initialiser에 [String : Any]에서 변경해야합니다 다음은 샘플 작업 코드는 여기에

public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil) 

스위프트 4.0

에 대한 initialiser 문/기능입니다 [NSAttributedStringKey : Any]?

로 변경됩니다.

let label = UILabel() 
    let labelText = "String Text" 
    let strokeTextAttributes = [ 
     NSAttributedStringKey.strokeColor : UIColor.black, 
     NSAttributedStringKey.foregroundColor : UIColor.white, 
     NSAttributedStringKey.strokeWidth : -2.0, 
     NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18) 
     ] as [NSAttributedStringKey : Any] 
    label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes) 

지금 애플이 메모를 보면 :

0

NSAttributedStringKey.strokeColor.rawValueNSAttributedString - Creating an NSAttributedString Object 유형 String

NSAttributedStringKey.strokeColor이다 유형 NSAttributedStringKeyString을 변환 그래서 그없는 NSAttributedStringKey

입니다 . 아래처럼 사용할 수 있습니다

let strokeTextAttributes: [NSAttributedStringKey : Any] = [ 
    NSAttributedStringKey.strokeColor : UIColor.black, 
    NSAttributedStringKey.foregroundColor : UIColor.white, 
    NSAttributedStringKey.strokeWidth : -2.0, 
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18) 
]