简体   繁体   中英

How do you add an attribute to an Unicode string in Swift?

How do you add attribute to a UNICODE string in Swift?

NSMakeRange seems to expect String in bytes for a variable byte length UNICODE string.

Any way to solve this? Thanks in advance.

var s:NSMutableAttributedString = NSMutableAttributedString(string: "வாங்க வாங்க வணக்கமுங்க")
s.string[0...2]
s.addAttribute(NSForegroundColorAttributeName, value:UIColor(red:0.0, green:1.0, blue:0.0, alpha:1.0), range:NSMakeRange(0,3))

UPDATED EXAMPLE:

let text = "வாங்க வாங்க வணக்கமுங்க"
var startOfWord = advance(text.startIndex, 4)
var endOfWord = advance(startOfWord, 3)
var highlightRange = startOfWord..<endOfWord
text[startOfWord..<endOfWord]

let attrText = NSMutableAttributedString(string:text)
attrText.addAttribute(NSForegroundColorAttributeName, value:UIColor(red:0.0, green:1.0, blue:0.0, alpha:1.0), range:highlightRange)

How do construct NSRange from swift Range?

I created a small extension for String which works for both Index based and Int based Ranges.

extension String {
    func NSRangeFromRange(swiftRange: Range<Index>) -> NSRange {
        let start = swiftRange.startIndex.samePositionIn(utf16)
        let end = swiftRange.endIndex.samePositionIn(utf16)
        return NSRange(location: utf16.startIndex.distanceTo(start), length: start.distanceTo(end))
    }
    func NSRangeFromRange(swiftRange: Range<Int>) -> NSRange {
        let indexRange = Range(start: startIndex.advancedBy(swiftRange.startIndex), end: startIndex.advancedBy(swiftRange.endIndex))
        return NSRangeFromRange(indexRange)
    }
}

Note: The function is on the String class because we need the strings UTF16View to convert between the Unicode-aware Range<Index> and the non-Unicode-aware NSRange .

I hope the below function may help you

func findAndAddAttributeString(str: String, query : String) {

    let strASNSString = str as NSString

    println("employeeIdAsNSString, \(strASNSString)")

    var attributeDictionary = NSMutableDictionary(objects: [UIColor.grayColor(), UIFont.systemFontOfSize(17)], forKeys: [NSForegroundColorAttributeName, NSFontAttributeName])


    println("attributeDictionary, \(attributeDictionary)")

    var attributedEmployeeId = NSMutableAttributedString(string: strASNSString, attributes: attributeDictionary)

    println("attributedEmployeeId = \(attributedEmployeeId)")

    var error:NSError?

    var regex = NSRegularExpression.regularExpressionWithPattern(query, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)
    println("regex = \(regex)")

    var range = NSMakeRange(0, strASNSString.length)
    println("range = \(range)")

    regex.enumerateMatchesInString(strASNSString, options: nil, range: range, usingBlock:{ (textCheckingResult, MatchingFlags, unsafePointer) in
        println("textCheckingResult \(textCheckingResult.rangeAtIndex(0))")
        var subStringRange = textCheckingResult.rangeAtIndex(0)
        attributedEmployeeId.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: subStringRange)
        })
}

You can convert a swift String to Swift NSString by

var strAsNSString = "வாங்க வாங்க வணக்கமுங்க" as NSString

And then you can create NSMutableAttributedString.

Something like this might work:

let text = "வாங்க வாங்க வணக்கமுங்க"
var startOfWord = advance(text.startIndex, 5)
var endOfWord = advance(startOfWord, 5)
var range = startOfWord..<endOfWord

Even if some more work is required to figure out how far to advance (if you are looking for just one known word you can directly get it with NSRangeFromString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM