简体   繁体   English

iOS Swift相对字体大小

[英]iOS Swift Relative font size

I have a UITextView, and I want to change its font size. 我有一个UITextView,我想改变它的字体大小。 however, I want it to change relatively since it pulls from a file that has multiple font sizes in it and I want it to change accordingly. 但是,我希望它相对更改,因为它从具有多个字体大小的文件中提取并且我希望它相应地更改。 for example, I have a word in font size 36 and one in font size 12 and I want to scale them by 0.75% to 27 and 9 respectively. 例如,我有一个字体大小为36的字和一个字体大小为12的字,我想将它们分别缩放0.75%到27和9。

If I try: 如果我尝试:

textview.font = UIFont(name: textview.font.fontName, size: 20)

it will only change the entire UITextView font size. 它只会改变整个UITextView字体大小。

thanks! 谢谢!

You can use this extension: 您可以使用此扩展程序:

extension NSAttributedString {
  @warn_unused_result
  func scaleBy(scale: CGFloat) -> NSAttributedString {
    let scaledAttributedString = NSMutableAttributedString(attributedString: self)
    scaledAttributedString.enumerateAttribute(NSFontAttributeName, inRange: NSRange(location: 0, length: scaledAttributedString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (value, range, _) in
        if let oldFont = value as? UIFont {
            let newFont = oldFont.fontWithSize(oldFont.pointSize * scale)
            scaledAttributedString.removeAttribute(NSFontAttributeName, range: range)
            scaledAttributedString.addAttribute(NSFontAttributeName, value: newFont, range: range)
        }
    }
    return scaledAttributedString
  }
}

Then just call something like: 然后打电话给:

textField.attributedText = textField.attributedText!.scaleBy(0.5)

Example: 例:

在操场上的例子

You would have to write (or find) a parser for the rich text format file that could extract the font size data for each text element (I think this would be the \\fsN tags in most cases) and then use that number (multiplied by 0.75) to set the size of each word or phrase individually. 您必须为富文本格式文件编写(或查找)解析器,该文件可以提取每个文本元素的字体大小数据(我认为在大多数情况下这将是\\fsN标记)然后使用该数字(乘以0.75)单独设置每个单词或短语的大小。 You could use an attributed string if the differently sized words need to be recombined into a single string, but that wouldn't be necessary if each word or phrase was in a separate label. 如果需要将不同大小的单词重新组合成单​​个字符串,则可以使用属性字符串,但如果每个单词或短语都在单独的标签中,则不需要。

Personally, I would disregard the font sizes of the source data and impose a layout within the app that looks nice, if that's an option. 就个人而言,我会忽略源数据的字体大小,并在应用程序中强加一个看起来不错的布局,如果这是一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM