-1

I want to make the letter font size bigger and number font size smaller in UILabel's text. How can I do?

I tried to use NSAttributedString, but it seems to receive a confirmed range to change. This can not meet my needs。

Thanks a lot

skyrealman
  • 33
  • 3
  • 1
    Since that's likely what you'll need to do, maybe you can write an algorithm that *meet your needs*. Update the various ranges as needed based on their contents? –  Nov 17 '17 at 15:39
  • https://stackoverflow.com/questions/1417346/iphone-uilabel-containing-text-with-multiple-fonts-at-the-same-time – Adrian Nov 17 '17 at 15:55

2 Answers2

2

What is wrong with NSAttributedString?

This is a String extension returning an attributed string. You can pass the font size for letter and digit.

It uses Regular Expression to find the numeric ranges

extension String {

    func attributedString(letterSize: CGFloat, digitSize: CGFloat) -> NSAttributedString
    {
        let pattern = "\\d+"
        let regex = try! NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: self, range: NSRange(location: 0, length: self.count))
        let attributedString = NSMutableAttributedString(string: self, attributes: [.font : UIFont.systemFont(ofSize: letterSize)])
        matches.forEach { attributedString.addAttributes([.font : UIFont.systemFont(ofSize: digitSize)], range: $0.range) }
        return attributedString.copy() as! NSAttributedString
    }
}

And use it

let string = """
Apple Computer Inc.
1 Infinite Loop Cupertino
CA 95014
(800) 275-2273
"""

let attributedString = string.attributedString(letterSize: 14.0, digitSize: 18.0)

Result:

enter image description here

vadian
  • 274,689
  • 30
  • 353
  • 361
0

In that case you could use a regular expression to get ranges of numbers to retrieve their ranges and set their attributes accordingly.

MartinM
  • 832
  • 6
  • 12