Search code examples
swiftrandomstringwithformat

How to create random string with multiple formats?


I need to create a random string with format which can convert any string(including parenthesis() to another color on swift: for example:

Hey (Hey) : First part 'Hey' is fine, but I want to change : (Hey) to a different color same goes if I choose another string

Hi (What's Up) ....

And tried the following

let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 50)))

let color = UIColor(white: 0.2, alpha: 1)
let attributedTextCustom = NSMutableAttributedString(string: "(\(String())", attributes: [.font: UIFont(name:"AvenirNext-Medium", size: 16)!, .foregroundColor: color]))
attributedTextCustom.append(NSAttributedString(string: " (\(String())", attributes: [.font: UIFont(name: "AvenirNext-Regular", size: 12)!, .foregroundColor: UIColor.lightGray]))
label.attributedText = attributedTextCustom

Something like this is the behavior I am looking for (just for demostration...):

enter image description here


Solution

  • You can use a regex "\\((.*?)\\)" to find the range of the word between the parentheses and add the color attribute to a NSMutableAttributedString:

    let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 50)))
    let sentence = "Hello (Playground)"
    let mutableAttr = NSMutableAttributedString(string: sentence, attributes: [.font: UIFont(name:"AvenirNext-Medium", size: 16)!, .foregroundColor: UIColor.black])
    
    if let range = sentence.range(of: "\\((.*?)\\)", options: .regularExpression) {
        let color = UIColor(white: 0.2, alpha: 1)
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name:"AvenirNext-Medium", size: 16)!, .foregroundColor: color]
        mutableAttr.addAttributes(attributes, range: NSRange(range, in: sentence))
        label.attributedText = mutableAttr
    }