iOS涓璶sattributedstring鎬庝箞浣跨敤
鍦?iOS 涓紝NSAttributedString 鏄竴绉嶇敤浜庡湪鏂囨湰涓坊鍔犳牱寮忓拰灞炴€х殑绫汇€備綘鍙互浣跨敤 NSAttributedString 鏉ヨ缃枃鏈殑瀛椾綋銆侀鑹层€佽闂磋窛銆佷笅鍒掔嚎绛夊睘鎬с€?/p>
涓嬮潰鏄浣曚娇鐢?NSAttributedString 鐨勪竴涓ず渚嬶細
// 鍒涘缓涓€涓?NSMutableAttributedString 瀵硅薄
let attributedString = NSMutableAttributedString(string: "Hello, World!")
// 璁剧疆鏂囨湰鐨勫瓧浣撳拰棰滆壊
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 20),
.foregroundColor: UIColor.red
]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
// 璁剧疆鏂囨湰鐨勪笅鍒掔嚎
let underlineAttributes: [NSAttributedString.Key: Any] = [
.underlineStyle: NSUnderlineStyle.single.rawValue
]
attributedString.addAttributes(underlineAttributes, range: NSRange(location: 0, length: 5))
// 璁剧疆鏂囨湰鐨勮闂磋窛
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
// 灏?NSAttributedString 搴旂敤鍒?UILabel 涓?/span>
let label = UILabel()
label.attributedText = attributedString
鍦ㄤ笂闈㈢殑绀轰緥涓紝鎴戜滑棣栧厛鍒涘缓浜嗕竴涓?NSMutableAttributedString 瀵硅薄锛屽苟璁剧疆浜嗕竴浜涘睘鎬э紝鏈€鍚庡皢杩欎簺灞炴€у簲鐢ㄥ埌浜嗕竴涓?UILabel 涓€?/p>
閫氳繃浣跨敤 NSAttributedString锛屼綘鍙互杞绘澗鍦板湪鏂囨湰涓坊鍔犲悇绉嶆牱寮忓拰灞炴€э紝浣夸綘鐨勫簲鐢ㄧ晫闈㈡洿鍔犱赴瀵屽拰缇庤銆?/p>
相关问答