Skip to content

Commit

Permalink
Fix crash due to range out of bounds - caused by #107
Browse files Browse the repository at this point in the history
  • Loading branch information
polqf committed Sep 4, 2016
1 parent 3fdcb84 commit f27a513
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
7 changes: 4 additions & 3 deletions ActiveLabel/ActiveBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,17 @@ struct ActiveBuilder {
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

guard let maxChar = maxChar where word.characters.count > maxChar else {
let newRange = (text as NSString).rangeOfString(word)
let element = ActiveElement.create(with: type, text: word)
elements.append((match.range, element, type))
elements.append((newRange, element, type))
continue
}

let trimmedWord = word.trim(to: maxChar)
text = text.stringByReplacingOccurrencesOfString(word, withString: trimmedWord)
let element = ActiveElement.URL(original: word, trimmed: trimmedWord)

let newRange = NSRange(location: match.range.location, length: trimmedWord.characters.count + 1)
let newRange = (text as NSString).rangeOfString(trimmedWord)
let element = ActiveElement.URL(original: word, trimmed: trimmedWord)
elements.append((newRange, element, type))
}
return (elements, text)
Expand Down
5 changes: 4 additions & 1 deletion ActiveLabel/ActiveLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,9 @@ typealias ElementTuple = (range: NSRange, element: ActiveElement, type: ActiveTy

addLinkAttribute(mutAttrString)
textStorage.setAttributedString(mutAttrString)
_customizing = true
text = mutAttrString.string
_customizing = false
setNeedsDisplay()
}

Expand Down Expand Up @@ -291,7 +294,7 @@ typealias ElementTuple = (range: NSRange, element: ActiveElement, type: ActiveTy
}

/// use regex check all link ranges
private func parseTextAndExtractActiveElements(attrString: NSMutableAttributedString) -> String{
private func parseTextAndExtractActiveElements(attrString: NSMutableAttributedString) -> String {
var textString = attrString.string
var textLength = textString.utf16.count
var textRange = NSRange(location: 0, length: textLength)
Expand Down
8 changes: 8 additions & 0 deletions ActiveLabelTests/ActiveTypeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -326,4 +326,12 @@ class ActiveTypeTests: XCTestCase {
XCTAssertEqual(currentElementString, "are")
XCTAssertEqual(currentElementType, customEmptyType)
}

func testStringTrimming() {
let text = "Tweet with long url: https://twitter.com/twicket_app/status/649678392372121601 and short url: https://hello.co"
label.urlMaximumLength = 30
label.text = text

XCTAssertNotEqual(text.characters.count, label.text!.characters.count)
}
}

0 comments on commit f27a513

Please sign in to comment.