20

Swift アプリのテキストに下線を追加しようとしています。これは私が現在持っているコードです:

let text = NSMutableAttributedString(string: self.currentHome.name)

let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]

text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text

しかし、次のエラーが表示されますtext.addAttributes

NSStringと同一ではありませんNSObject

列挙型に含まれる属性を Swift の NSMutableAttributedString に追加するにはどうすればよいですか?

4

4 に答える 4

52

UILabel下線付きのテキストを作成する完全な例を次に示します。

スウィフト5:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.single.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

スウィフト 4:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

スウィフト 2:

Swift では、 を受け取るIntメソッドに を渡すNSNumberことができるため、 への変換を削除することで、これを少しきれいにすることができますNSNumber

text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))

注: この回答は以前は元の質問で使用されていましたが、Xcode 6.1 の時点でプロパティに置き換えられたため、toRaw()現在は正しくありません。toRaw()rawValue

于 2014-09-02T00:21:27.403 に答える
14

実際の破線が必要な場合は、OR | を使用する必要があります。以下のような PatternDash と StyleSingle 列挙型の生の値:

let dashed     =  NSUnderlineStyle.PatternDash.rawValue | NSUnderlineStyle.StyleSingle.rawValue

let attribs    = [NSUnderlineStyleAttributeName : dashed, NSUnderlineColorAttributeName : UIColor.whiteColor()];

let attrString =  NSAttributedString(string: plainText, attributes: attribs)
于 2015-06-03T22:30:24.030 に答える
3

メソッドが必要であることがわかりましたtoRaw()-これは機能します:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
于 2014-09-01T19:32:42.370 に答える