You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

动态适配屏幕分辨率设置字体大小、样式及粗细的问题求助

解决iOS字体加粗+屏幕分辨率自适应问题

嘿,我来帮你搞定这个字体的问题!你现在用的UIFont.preferredFont(forTextStyle:)确实能让字体跟随系统动态类型和屏幕分辨率自适应大小,但它默认返回的是常规字重的字体,所以才看不到加粗效果。下面给你两种实用的解决方式:

方法1:直接修改字体描述符

针对单个字体,你可以先获取对应文本样式的字体描述符,再给它添加加粗特性,最后生成新字体:

// 处理标题1(加粗+自适应)
let title1Descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .title1)
let boldTitle1Descriptor = title1Descriptor.withSymbolicTraits(.traitBold) ?? title1Descriptor
title_home.font = UIFont(descriptor: boldTitle1Descriptor, size: 0)

// 处理标题2(同理)
let title2Descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .title2)
let boldTitle2Descriptor = title2Descriptor.withSymbolicTraits(.traitBold) ?? title2Descriptor
subtitle_home.font = UIFont(descriptor: boldTitle2Descriptor, size: 0)
subtitle1_home.font = UIFont(descriptor: boldTitle2Descriptor, size: 0)
subtitle2_home.font = UIFont(descriptor: boldTitle2Descriptor, size: 0)

这里size: 0是关键——它会自动使用描述符里的默认大小,完美适配屏幕分辨率和系统字体设置。

方法2:封装成便捷方法(推荐)

如果多个地方需要用到加粗的自适应字体,不如封装一个工具方法,复用起来更省心:

extension UIFont {
    static func preferredBoldFont(forTextStyle style: UIFont.TextStyle) -> UIFont {
        let baseDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
        // 尝试添加加粗特性,如果失败就返回原字体
        guard let boldDescriptor = baseDescriptor.withSymbolicTraits(.traitBold) else {
            return UIFont.preferredFont(forTextStyle: style)
        }
        return UIFont(descriptor: boldDescriptor, size: 0)
    }
}

// 使用的时候超简单
title_home.font = .preferredBoldFont(forTextStyle: .title1)
subtitle_home.font = .preferredBoldFont(forTextStyle: .title2)
subtitle1_home.font = .preferredBoldFont(forTextStyle: .title2)
subtitle2_home.font = .preferredBoldFont(forTextStyle: .title2)

这样设置后,你的标题不仅会自动加粗,还能完美跟随屏幕分辨率调整大小,甚至支持用户在系统设置里调整字体大小的动态变化哦!

内容的提问来源于stack exchange,提问作者Navya

火山引擎 最新活动