How do I uses addAttribute and NSRANGE in swift 3
Asked Answered
T

1

7

Hi I'm trying to use addAttribute in Swift3.

I want set bold only IDNAME.

Here is what I am trying to this.

let boldUsername = NSMutableAttributedString(string: "IDNAME hi nice 2 meet you :D #HELLOW")


//            boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: (boldUsername.string as NSString).range(of: " "))

            boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: NSRange(location: 0, length: 5))

How do I get index of the IDNAME i.e different every time?

-> Is there a way to split space and get index?

Touched answered 1/10, 2016 at 8:35 Comment(5)
Can you please explain "How do I get string count", what does it mean?Kirovabad
Have you checked this ?Reggiereggis
@NiravD I want get index of strings. e.g > "IDNAME hi ~~~" I is index 0. E is index 5. So How do I get the end of ID's index? Thanks for the replyTouched
you means idname is run time name and you want the range of its. right?Kirovabad
@NiravD yeah right exactly. I'm making an comment view.Touched
K
23

You need to do something like this.

let personName = "Black"
let wholeStr = "\(personName) hi nice 2 meet you :D #HELLOW"
let boldUsername = NSMutableAttributedString(string: wholeStr)
boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: (wholeStr as NSString).range(of: personName))
Kirovabad answered 1/10, 2016 at 16:46 Comment(4)
very easy to understand. nice answerParanoiac
@Vats Welcome & Thanks :)Kirovabad
Might wanna change value: UIFont(name: "SFUIText-Bold", size: 14)! to value: UIFont.boldSystemFont(ofSize: 14) - pretty sure the former will crash at runtime (force-unwrapping a nil optional).Grievous
@Grievous Thanks for the suggestion mate :), but this question about addAttribute and rangeKirovabad

© 2022 - 2024 — McMap. All rights reserved.