ios uilabel 垂直居中_UILabel中富文本垂直不居中的解决方案

在iOS开发中,遇到使用富文本后UILabel文本垂直居中对齐出现偏差的问题。通过设置NSAttributedStringKey.baselineOffset属性,调整文本基线,可以解决文本偏下并使其重新垂直居中。具体做法是在创建富文本后,为整个字符串范围设置baselineOffset属性,例如设置为3,以使文本上移,实现居中效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如下图所示,收益率label由于数字部分是红色,所以使用到了富文本,但是很明显,label中的文本相对label垂直方向不再居中了,位置明显靠下了。

b0156365d725?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

以下是swift代码

let rate_return_tip = NSMutableAttributedString(string: " 收益率\(String(format: "%.3f", rate_of_return))% ")

rate_return_tip.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSMakeRange(5, rate_return_tip.length-5))

rate_return_tip.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSMakeRange(0, rate_return_tip.length))

以下是swift解决方案代码

let rate_return_tip = NSMutableAttributedString(string: " 收益率\(String(format: "%.3f", rate_of_return))% ")

rate_return_tip.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSMakeRange(5, rate_return_tip.length-5))

rate_return_tip.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSMakeRange(0, rate_return_tip.length))

# 调整文本基线,在我这里,因为是垂直方向明显靠下了,所以向上调整了3个单位

rate_return_tip.addAttribute(NSAttributedStringKey.baselineOffset, value:3, range: NSMakeRange(0, rate_return_tip.length))

如下是调整后的效果

b0156365d725?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值