如何在iOS故事板中使用自定义字体来表示动态类型辅助功能大小

时间:2016-02-12 05:51:29

标签: ios swift uistoryboard xcode-storyboard

如何使用dynamic type text style"标题1"并在故事板中为UILabel设置字体面为内置字体Chalkboard SE?

我需要尊重iOS中的动态类型大小(Apple自iOS 7以来一直鼓励这个吗?)我还需要使用内置字体Chalkboard SE,默认情况下不会用于"文本样式"字体。我目前正在使用图片中显示的自定义字体,但需要字体根据用户的动态类型 / 辅助功能大小首选项更改大小与所有文本样式字体一样。最好的文本样式选项是标题1 ,但字体/字体是不可接受的。

Font menu in Xcode. Custom checked and Title 1 highlighted

3 个答案:

答案 0 :(得分:19)

虽然您无法通过Storyboard指定自定义字体和首选文本样式,但以编程方式为自定义字体指定动态类型大小并不困难:

<强>夫特:

$bind = array(':increment_id' => $orderIncrementId);

收到let pointSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFont‌​TextStyleTitle1).poi‌​ntSize let customFont = UIFont(name: "Chalkboard SE", size: pointSize) 后,请使用相同的代码更新标签的字体。

对象C:

UIContentSizeCategoryDidChangeNotification

答案 1 :(得分:1)

我们必须添加相关UIFramework的所有扩展,为此我们必须使用iOS-11 +中的自定义字体的动态字体大小,例如UILabel,UIButton,UITextField,UITextView。代码在Swift 4.2中给出。我们只需要使用这些自定义类而不是本机ios类即可查看应用程序中动态字体的效果。

首先是标签:

class AppLabel: UILabel {

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if #available(iOS 11.0, *)  {

        self.font = UIFontMetrics.default.scaledFont(for: self.font)
        self.adjustsFontForContentSizeCategory = true
        // Fallback on earlier versions
    } else {
        // Fallback on earlier versions
    }
  }

}

这里第二个是UIButton:

class AppButton: UIButton {

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if #available(iOS 11.0, *) {

        self.titleLabel?.font = UIFontMetrics.default.scaledFont(for: self.titleLabel?.font ?? UIFont())
        self.titleLabel?.adjustsFontForContentSizeCategory = true
    } else {
        // Fallback on earlier versions 
    }
  }
}

第3个是UITextField:

class AppTextField: UITextField {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if #available(iOS 11.0, *) {

        self.font = UIFontMetrics.default.scaledFont(for: self.font ?? UIFont())
        self.adjustsFontForContentSizeCategory = true
    } else {
        // Fallback on earlier versions
    }
  }
}

UITextView中的最后一个:

class AppTextView: UITextView {

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if #available(iOS 11.0, *) {

        self.font = UIFontMetrics.default.scaledFont(for: self.font ?? UIFont())
        self.adjustsFontForContentSizeCategory = true
    } else {
        // Fallback on earlier versions
    }
  }
}

答案 2 :(得分:0)

尝试使用我的解决方案,而无需收听 NSNotification.Name.UIContentSizeCategoryDidChange

只需在任何UIView或UITableViewCell上覆盖 traitCollectionDidChange ,并使用类似的TextStyle更新/计算fontsize。

您可以使用任何模拟设备和MacOS上的辅助功能检查器进行简单测试。