ios swift: Is it possible to change the font style of a certain word in a string?

后端 未结 3 965
鱼传尺愫
鱼传尺愫 2020-12-03 12:38

I am extracting from a DB contents as strings. With a method I extract the longest word out of this string.

Now I would like to print out the entire string to a tex

3条回答
  •  长情又很酷
    2020-12-03 12:58

    If you already know the longest word you have to get the range of that word in the string. I prefer the NSString method rangeOfString: for this.

    You then create a NSMutableAttributedString from the string, with your default attributes. Finally you apply highlighting attributes to the range you figured out earlier.

    let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar"
    let longestWord = "VeryLongWord"
    
    let longestWordRange = (longString as NSString).rangeOfString(longestWord)
    
    let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)])
    
    attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange)
    
    
    label.attributedText = attributedString
    

    Update for Swift 5.0

    let longestWordRange = (longString as NSString).range(of: longestWord)
    
    let attributedString = NSMutableAttributedString(string: longString, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 20)])
    
    attributedString.setAttributes([NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor : UIColor.red], range: longestWordRange)
    

    Which looks like this in my playground:

    enter image description here

提交回复
热议问题