如何在NSMutableAttributedString中传递两个字符串

时间:2017-03-19 02:29:40

标签: ios swift xcode uilabel nsattributedstring

< p>我有两个< code> UILabel< / code>在xib文件上,我正在使用plist文件来编辑其文本。< / p> < p>我想增加两个< code> UILabels< / code>的行距。 "标题"和"详细信息"。 < / p为H. < p>为了增加行间距,我实现了< code> NSMutableAttributedString< / code>。但是我不知道如何在一个类中传递两个字符串。< / p> < p>该问题的任何解决方案?< / p> < pre>< code> class PlaySheetCellLeft:UITableViewCell {     @IBOutlet var LBLTitle:UILabel!     @IBOutlet var LBLDetail:UILabel!     var message:[String:Any]? {         didSet {             警卫让msg = self.message else {return}             让title = msg ["标题"]为!串             self.LBLTitle.text = title             让detail = msg [" detail"]为!串             self.LBLDetail.text =详情             let paragraphStyle = NSMutableParagraphStyle()             paragraphStyle.lineSpacing = 10             //错误代码             let attrString = NSMutableAttributedString(string:title,string:details)             attrString.addAttribute(NSParagraphStyleAttributeName,value:paragraphStyle,range:NSMakeRange(0,attrString.length))             LBLTitle.attributedText = attrString         }    } < /代码>< /预>

2 个答案:

答案 0 :(得分:0)

我相信您正在尝试从两个不同的字符串创建一个NSMutableAttributedString。但是你应该做的是创建两个独立的NSMutableAttributedString实例 - 一个用于标题,一个用于细节。

答案 1 :(得分:0)

简单易行

如果你使用不同的标题标题和&然后详细说明

// For title 
let attrTitleString = NSMutableAttributedString(string: title)
attrTitleString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrTitleString.length))
LBLTitle.attributedText = attrString

// For detail 
let attrDetailsString = NSMutableAttributedString(string: details)
attrDetailsString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrDetailsString.length))
LBLDetail.attributedText = attrDetailsString

表示单个标签

let labelString = "\(title)\n\(details)"
let attrString = NSMutableAttributedString(string: labelString)

// Set common attribute for both title & detail (according to your code)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

// You can also set differnt attribute for title & details
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(<... set range for title...>))

attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(<...Set range for details....>))

<you label instance - LBLTitle or LBLDetail>.attributedText = attrString