简体   繁体   中英

iOS Swift Relative font size

I have a UITextView, and I want to change its font size. 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.

If I try:

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

it will only change the entire UITextView font size.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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