2017-10-09 22 views
2

私はスイフト3からスウィフト4に移行しています。私はラベルに非常に特殊なテキストプロパティを与えているUILabelsを持っています。私は、strokeTextAttributesが初期化されているときに 'オプション値をアンラップしている間に'予期せず見つからないnil 'エラーを受け取っています。私は率直になるために完全に失われています。Swift 4ラベル属性

swift 3のthe strokeTextAttributesは[String:Any]でしたが、私がそれを以下に変更するまでエラーをスローしました。

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'sを使うことができるので、範囲は私が知る限りサポートされていません。 – XML

0

スイフト4はあなた自身に解決策を提案します。 Swift 4.0では、属性付き文字列accept key typeがNSAttributedStringKeyのjson(辞書)を受け入れます。ですから、スウィフト4.0でAttributedStringため[NSAttributedStringKey : Any]

初期化子に[String : Any]からそれを変更する必要がありますがここではサンプル動作するコードです。ここ

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

スウィフト4.0

のための初期化子の文/機能です [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) 

は今、アップルからこのノートを見て:NSAttributedString - Creating an NSAttributedString Object

0

NSAttributedStringKey.strokeColor.rawValueはタイプString

NSAttributedStringKey.strokeColorのあるタイプNSAttributedStringKey

NSAttributedStringKeyStringを変換するので、そのことができません。代わりに

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