如何为UIFont设置行高?该操作是否可行?
能否为UIFont设置行高?答案是不行,正确做法看这里
直接给UIFont设置行高是不可行的,背后有明确的设计逻辑:
- UIFont的
lineHeight是只读属性,它是字体文件本身固有的特性,由字体的原始设计决定,你无法通过赋值修改它(就像你尝试的font.lineHeight = 12必然无效)。 - UIFont类本身也没有提供设置最小/最大行高的相关属性,因为行高属于文本排版层面的需求,和字体本身的特性无关。
正确控制行高的方式
要实现自定义行高,你需要通过文本排版样式来设置,具体是用NSMutableParagraphStyle配合富文本(NSAttributedString)来实现,下面是Swift的示例代码:
// 先创建你需要的字体 let targetFont = UIFont.systemFont(ofSize: 12, weight: .bold) // 创建段落样式,设置行高相关属性 let paragraphStyle = NSMutableParagraphStyle() // 方式1:通过lineSpacing调整行高(最终行高 = 字体固有lineHeight + lineSpacing) // 比如想要总高度18,字体固有lineHeight是14,那么lineSpacing设为4 paragraphStyle.lineSpacing = 4 // 方式2:通过lineHeightMultiple设置倍数行高(比如1.5倍原行高) // paragraphStyle.lineHeightMultiple = 1.5 // 组合成富文本属性 let textAttributes: [NSAttributedString.Key: Any] = [ .font: targetFont, .paragraphStyle: paragraphStyle ] // 创建富文本并赋值给UILabel或UITextView let attributedText = NSAttributedString(string: "需要展示的文本内容", attributes: textAttributes) yourLabel.attributedText = attributedText // yourTextView.attributedText = attributedText
额外提示
- 如果你使用的是UILabel,记得要设置
yourLabel.numberOfLines = 0来支持多行文本显示,行高设置才会生效。 - UITextView默认支持多行,直接赋值富文本即可生效。
内容的提问来源于stack exchange,提问作者久美子
相关产品推荐
相关产品推荐

