扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

iOS涓璶sattributedstring鎬庝箞浣跨敤

扬州沐宇科技
2024-04-26 23:03:46
iOS

鍦?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>

扫码添加客服微信