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
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
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:
In that case you could use a regular expression to get ranges of numbers to retrieve their ranges and set their attributes accordingly.