Ios Swift-下一行的属性字符串背景色
我有一个标签,我希望在第1行显示一些单词,在第2行显示一些单词。我可以通过在字符串之间放置“\n”来实现它。第2行上的单词是带有背景色的属性字符串,但是背景色从第1行开始 有没有办法,我可以在第二行得到背景色 下面是代码:Ios Swift-下一行的属性字符串背景色,ios,swift,string,nsattributedstring,Ios,Swift,String,Nsattributedstring,我有一个标签,我希望在第1行显示一些单词,在第2行显示一些单词。我可以通过在字符串之间放置“\n”来实现它。第2行上的单词是带有背景色的属性字符串,但是背景色从第1行开始 有没有办法,我可以在第二行得到背景色 下面是代码: 简单解决方案:-只需在一行字符串中添加/n即可解决问题 let attributedString = NSMutableAttributedString(string: "Line 1 Text\n" ?? "") let attributesForNonSelectedRo
简单解决方案:-只需在一行字符串中添加/n即可解决问题
let attributedString = NSMutableAttributedString(string: "Line 1 Text\n" ?? "")
let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
attributedString.append(myTitle)
searchTitleLabel.lineBreakMode = .byWordWrapping
searchTitleLabel.numberOfLines = 0
searchTitleLabel.attributedText = attributedString
通过约束解决方案:
为什么不尝试通过提供前导、顶部和高度约束来设置标签的约束,就可以实现
我写了这个问题。我所要做的就是将“\n”放在第1行的后面,而不是第2行的前面,这样就解决了背景色问题
let attributedString = NSMutableAttributedString(string: "Line 1 Text \n" ?? "")
let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
attributedString.append(myTitle)
searchTitleLabel.lineBreakMode = .byWordWrapping
searchTitleLabel.numberOfLines = 0
searchTitleLabel.attributedText = attributedString
let attributedString = NSMutableAttributedString(string: "Line 1 Text \n" ?? "")
let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
attributedString.append(myTitle)
searchTitleLabel.lineBreakMode = .byWordWrapping
searchTitleLabel.numberOfLines = 0
searchTitleLabel.attributedText = attributedString