I looked around SO and couldn't find this exact problem, despite there being a few questions with similar titles.
All I want to do is have some matching text on UILabel be drawn in BOLD. I'm using it when I'm searching for objects, it should 'bolden' the search term. To this aim, I wrote the following code:
extension String {
func boldenOccurrences(of searchTerm: String?, baseFont: UIFont, textColor: UIColor) -> NSAttributedString {
let defaultAttributes: [String : Any] = [NSForegroundColorAttributeName : textColor,
NSFontAttributeName: baseFont]
let result = NSMutableAttributedString(string: self, attributes: defaultAttributes)
guard let searchTerm = searchTerm else {
return result
}
guard searchTerm.characters.count > 0 else {
return result
}
// Ranges. Crash course:
//let testString = "Holy Smokes!"
//let range = testString.startIndex ..< testString.endIndex
//let substring = testString.substring(with: range) // is the same as testString
var searchRange = self.startIndex ..< self.endIndex //whole string
var foundRange: Range<String.Index>!
let boldFont = UIFont(descriptor: baseFont.fontDescriptor.withSymbolicTraits(.traitBold)!, size: baseFont.pointSize)
repeat {
foundRange = self.range(of: searchTerm, options: .caseInsensitive , range: searchRange)
if let found = foundRange {
// now we have to do some stupid stuff to make Range compatible with NSRange
let rangeStartIndex = found.lowerBound
let rangeEndIndex = found.upperBound
let start = self.distance(from: self.startIndex, to: rangeStartIndex)
let length = self.distance(from: rangeStartIndex, to: rangeEndIndex)
log.info("Bolden Text: \(searchTerm) in \(self), range: \(start), \(length)")
let nsRange = NSMakeRange(start, length)
result.setAttributes([NSForegroundColorAttributeName : textColor,
NSFontAttributeName: boldFont], range: nsRange)
searchRange = found.upperBound ..< self.endIndex
}
} while foundRange != nil
return result
}
}
Everything "looks" fine. The log statement spits out what I expect and it's all good. However, when drawn on the UILabel, sometimes an entire string is set to bold, and I don't understand how that could be happening. Nothing in the code suggests this should be happening.
I set the result of this above method in a typical UITableCell configuration method (i.e. tableView(cellForRowAt indexPath:.... ) )
cell.titleLabel.attributedText = artist.displayName.emptyIfNil.boldenOccurrences(of: source.currentSearchTerm, baseFont: cell.titleLabel.font, textColor: cell.titleLabel.textColor)
Your primary issue is the cell reuse, maybe when a cell is reused keep your font bold as font, and that is why you have this issue, you can solve this in your cell prepareForReuse() method you can add
override func prepareForReuse() {
super.prepareForReuse()
//to fix ipad Error
self.titleLabel.font = UIFont(name: "YourBaseFont", size: yourFontSize)
}
Related
I'm trying to implement an editor that can handle hashtag while typing.
extension UITextView {
func resolveHashTags() {
if self.text.isEmpty {
let emptyString = NSMutableAttributedString(string: " ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.font: self.font!])
self.attributedText = emptyString
self.textColor = .black
self.text = ""
return
}
let cursorRange = selectedRange
let nsText = NSString(string: self.text)
let words = nsText.components(separatedBy: CharacterSet(charactersIn: "##ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_").inverted).filter({!$0.isEmpty})
self.textColor = .black
let attrString = NSMutableAttributedString()
attrString.setAttributedString(self.attributedText)
attrString.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.black], range: nsText.range(of: self.text))
var anchor: Int = 0
for word in words {
// found a word that is prepended by a hashtag!
// homework for you: implement #mentions here too.
let matchRange:NSRange = nsText.range(of: word as String, range: NSRange(location: anchor, length: nsText.length - anchor))
anchor = matchRange.location + matchRange.length
if word.hasPrefix("#") {
// a range is the character position, followed by how many characters are in the word.
// we need this because we staple the "href" to this range.
// drop the hashtag
let stringifiedWord = word.dropFirst()
if let firstChar = stringifiedWord.unicodeScalars.first, NSCharacterSet.decimalDigits.contains(firstChar) {
// hashtag contains a number, like "#1"
// so don't make it clickable
} else {
// set a link for when the user clicks on this word.
// it's not enough to use the word "hash", but you need the url scheme syntax "hash://"
// note: since it's a URL now, the color is set to the project's tint color
attrString.addAttribute(NSAttributedString.Key.link, value: "hash:\(stringifiedWord)", range: matchRange)
}
} else if !word.hasPrefix("#") {
}
}
self.attributedText = attrString
self.selectedRange = cursorRange
}
}
So this is the extension I'm using to create a hyperlink in UITextView. Called in func textViewDidChange(_ textView: UITextView)
So while typing if any word starts with #. It'll turn in hyperlinks and will change color to blue. After typing the intended word if you press space it goes back to black text. This is expected behavior.
But if you clear text and move your course back to hashtag word like this
it keeps extending hyperlink to the next word too.
any solution to keep hyperlinks to that word only. Anything typed after hashtag should be normal text
I finally figured it out.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
var shouldReturn = true
let selectedRange = textView.selectedRange
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText)
if !text.isEmpty && text != " " {
var userAttributes = [(NSAttributedString.Key, Any, NSRange)]()
attributedText.enumerateAttribute(.link, in: _NSRange(location: 0, length: textView.text.count), options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
if let url = value as? String, url.hasPrefix("user:") {
userAttributes.append((.link, value!, range))
}
}
if let userLink = userAttributes.first(where: {$0.2.contains(range.location - 1)}) {
attributedText.replaceCharacters(in: range, with: NSAttributedString(string: text, attributes: [NSAttributedString.Key.link : userLink.1, NSAttributedString.Key.font : textView.font as Any]))
textView.attributedText = attributedText
shouldReturn = false
} else {
attributedText.replaceCharacters(in: range, with: NSAttributedString(string: text, attributes: [NSAttributedString.Key.font : textView.font as Any]))
textView.attributedText = attributedText
textDidChange?(textView)
shouldReturn = false
}
textView.selectedRange = _NSRange(location: selectedRange.location + text.count, length: 0)
textViewDidChange(textView)
}
return shouldReturn
}
This way I have the control to update the link in between the word and it doesn't extend afterward to a new word.
Kerning is not working if i pass -0.36, if i take screen shot from iPhone and comparing with design the string is not matching the length.
func addCharacterSpacing(kernValue: Double = 1.15) {
if let labelText = text, labelText.count > 0 {
let attributedString = NSMutableAttributedString(string: labelText)
attributedString.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
attributedText = attributedString
}
}
Finally ended with up by creating #discardableResult func, that exactly match with screen shot from iPhone and comparing with design. Pass parms accordingly.
#discardableResult func applyAttributesWithKerning(_ text: String, font:UIFont, lineSpace: CGFloat, charSpace: CGFloat, color:UIColor) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpace
var attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle]
attrs[NSAttributedString.Key.kern] = charSpace
attrs[NSAttributedString.Key.font] = font
attrs[NSAttributedString.Key.foregroundColor] = color
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
append(boldString)
return self
}
This is a follow up to this question How can I change style of some words in my UITextView one by one in Swift?
Thanks to #Josh's help I was able to write a piece of code that highlights each word that begins with # - and do it one by one. My final code for that was:
func highlight (to index: Int) {
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches = regex!.matches(in: hashtagExplanationTextView.text, options: [], range: NSMakeRange(0, (hashtagExplanationTextView.text.characters.count)))
let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]
let titleDict2: NSDictionary = [NSForegroundColorAttributeName: UIColor.red]
let storedAttributedString = NSMutableAttributedString(string: hashtagExplanationTextView.text!, attributes: titleDict as! [String : AnyObject])
let attributedString = NSMutableAttributedString(attributedString: storedAttributedString)
guard index < matches.count else {
return
}
for i in 0..<index{
let matchRange = matches[i].rangeAt(0)
attributedString.addAttributes(titleDict2 as! [String : AnyObject], range: matchRange)
}
hashtagExplanationTextView.attributedText = attributedString
if #available(iOS 10.0, *) {
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
self.highlight(to: index + 1)
}
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.highlight(to: index + 1)
}
}
}
This works fine, but I would like to change the logic so that it does not highlight the # words, but highlights (one by one) words from preselected array of those words.
So I have this array var myArray:[String] = ["those","words","are","highlighted"] and how can I put it instead of regex match in my code?
I believe you are using regex to get an array of NSRange. Here, you need a slightly different datastructure like [String : [NSRange]]. Then you can use rangeOfString function to detect the NSRange where the word is located. You can follow the example given below for that:
let wordMatchArray:[String] = ["those", "words", "are", "highlighted"]
let labelText:NSString = NSString(string: "those words, those ldsnvldnvsdnds, are, highlighted,words are highlighted")
let textLength:Int = labelText.length
var dictionaryForEachWord:[String : [NSRange]] = [:]
for eachWord:String in wordMatchArray {
var prevRange:NSRange = NSMakeRange(0, 0)
var rangeArray:[NSRange] = []
while ((prevRange.location + prevRange.length) < textLength) {
let start:Int = (prevRange.location + prevRange.length)
let rangeEach:NSRange = labelText.range(of: eachWord, options: NSString.CompareOptions.literal, range: NSMakeRange(start, textLength-start))
if rangeEach.length == 0 {
break
}
rangeArray.append(rangeEach)
prevRange = rangeEach
}
dictionaryForEachWord[eachWord] = rangeArray
}
Now that you have an array of NSRange i.e, [NSRange] for each word stored in a dictionary, you can highlight each word accordingly in your UITextView.
Feel free to comment if you have any doubts regarding the implementation :)
For this new requirement you don't need a regex, you can just iterate over your array of words and use rangeOfString to find out if that string exists and set the attributes for the located range.
To match the original functionality, after you find a matching range you need to search again, starting from the end of that range, to see if there is another match later in your source text.
The proposed solutions so far suggest that you go through each word and then search them in the text view. This works, but you are traversing the text way too many times.
What I would suggest is to enumerate all the words in the text and see if they match any of the words to highlight:
class ViewController: UIViewController {
#IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
highlight()
}
func highlight() {
guard let attributedText = textView.attributedText else {
return
}
let wordsToHighlight = ["those", "words", "are", "highlighted"]
let text = NSMutableAttributedString(attributedString: attributedText)
let textRange = NSRange(location: 0, length: text.length)
text.removeAttribute(NSForegroundColorAttributeName, range: textRange)
(text.string as NSString).enumerateSubstrings(in: textRange, options: [.byWords]) { [weak textView] (word, range, _, _) in
guard let word = word else { return }
if wordsToHighlight.contains(word) {
textView?.textStorage.setAttributes([NSForegroundColorAttributeName: UIColor.red], range: range)
} else {
textView?.textStorage.removeAttribute(NSForegroundColorAttributeName, range: range)
}
}
textView.typingAttributes.removeValue(forKey: NSForegroundColorAttributeName)
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
highlight()
}
}
This should be fine for small texts. For long texts, going through everything on each change can really hurt performance. In that case, I'd recommend using a custom NSTextStorage subclass. There you would have better control over what range of text have changed and apply the highlight only to that section.
I want NSTextView object to react to Tab key hit by changing NSParagraphStyle spacing. And it does but EXTREMELY slow!!! In fact if I do this changes too quick (hit Tab key too fast), I eventually got glitches that sometimes even lead to crash. Here's the video: https://drive.google.com/open?id=0B4aMQXnlIOvCUXNjWTVXVkR3NHc. And another one: https://drive.google.com/open?id=0B4aMQXnlIOvCUDJjSEN0bFdqQXc
Fragment of code from my NSTextStorage subclass:
override func attributesAtIndex(index: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
return storage.attributesAtIndex(index, effectiveRange: range)
}
override func replaceCharactersInRange(range: NSRange, withString str: String) {
let delta = str.characters.count - range.length
beginEditing()
storage.replaceCharactersInRange(range, withString:str)
edited([.EditedCharacters, .EditedAttributes], range: range, changeInLength: delta)
endEditing()
}
override func setAttributes(attrs: [String : AnyObject]!, range: NSRange) {
beginEditing()
storage.setAttributes(attrs, range: range)
edited(.EditedAttributes, range: range, changeInLength: 0)
endEditing()
}
Fragment of code from my NSTextView subclass:
override func shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) -> Bool {
super.shouldChangeTextInRange(affectedCharRange, replacementString: replacementString)
guard replacementString != nil else { return true }
if replacementString == "\t" {
defer {
let selectedRangesValues = self.selectedRanges
var selectedRanges = [NSRange]()
for value in selectedRangesValues {
selectedRanges.append(value.rangeValue)
}
textController.switchToAltAttributesInRange(selectedRanges)
}
return false
}
return true
}
Fragment of code from my TextController which creates and applies alternative attributes:
func switchToAltAttributesInRange(ranges : [NSRange]) {
// get paragraph indexes from the ranges
var indexes = [Int]()
for range in ranges {
for idx in textStorage.paragraphsInRange(range) {
indexes.append(idx)
}
}
// change attributes for all the paragraphs in those ranges
for index in indexes {
let paragraphRange = textStorage.paragraphRangeAtIndex(index)
let element = elementAtIndex(index)
let altElementType = altElementTypeForElementType(element.type)
// change the attributes
let newAttributes = paragraphAttributesForElement(type: altElementType.rawValue)
self.textStorage.beginUpdates()
self.textStorage.setAttributes(newAttributes, range: paragraphRange)
self.textStorage.endUpdates()
}
}
func paragraphAttributesForElement(type typeString: String) -> [String : AnyObject] {
let elementPreset = elementPresetForType(elementType)
// set font
let font = NSFont (name: elementPreset.font, size: CGFloat(elementPreset.fontSize))!
// set attributes
let elementAttributes = [NSFontAttributeName: font,
NSParagraphStyleAttributeName : paragraphStyleForElementPreset(elementPreset, font: font),
NSForegroundColorAttributeName: NSColor.colorFromHexValue(elementPreset.color),
NSUnderlineStyleAttributeName : elementPreset.underlineStyle,
ElementAttribute.AllCaps.rawValue : elementPreset.allCaps]
return elementAttributes
}
func paragraphStyleForElementPreset(elementPreset : TextElementPreset, font : NSFont) -> NSParagraphStyle {
let sceneParagraphStyle = NSMutableParagraphStyle()
let spacing = elementPreset.spacing
let spacingBefore = elementPreset.spacingBefore
let headIndent = elementPreset.headIndent
let tailIndent = elementPreset.tailIndent
let cFont = CTFontCreateWithName(font.fontName, font.pointSize, nil)
let fontHeight = CTFontGetDescent(cFont) + CTFontGetAscent(cFont) + CTFontGetLeading(cFont)
sceneParagraphStyle.paragraphSpacingBefore = CGFloat(spacingBefore)
sceneParagraphStyle.paragraphSpacing = fontHeight * CGFloat(spacing)
sceneParagraphStyle.headIndent = ScreenMetrics.pointsFromInches(CGFloat(headIndent))
sceneParagraphStyle.tailIndent = ScreenMetrics.pointsFromInches(CGFloat(tailIndent))
sceneParagraphStyle.firstLineHeadIndent = sceneParagraphStyle.headIndent
sceneParagraphStyle.lineBreakMode = .ByWordWrapping
return sceneParagraphStyle
}
Time Profiler instrument shows a high peak when I press the Tab key. It says that NSTextStorage attributesAtIndex takes up to 40 ms each time I press the Tab key.
I checked: if I remove NSParagraphStyle changes, everything becomes normal. So the question is: how should I update paragraph styles?
Hmm... Didn't found such a solution neither in Apple docs or in Google... Just have experimented and turns out if I add textView.display() after call of self.textStorage.setAttributes, everything works fine!
UPDATE: setNeedsDisplay(invalidRect) does a much better job because you might redraw just a dirty portion of text view's visible rect
I've tried a couple of different methods and extensions after coming across them on S.O. to no avail. Is there a definitive way to bold only part of a UIButton.titleLabel?
These are some of the extensions I've tried:
func attributedText(fullStr: String, boldStr: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: fullStr as String, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(12.0)])
let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFontOfSize(12.0)]
// Part of string to be bold
attributedString.addAttributes(boldFontAttribute, range: NSMakeRange(0, boldStr.characters.count))
return attributedString
}
func boldRange(range: Range<String.Index>) {
if let text = self.attributedTitleForState(UIControlState.Normal) {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.startIndex.distanceTo(range.startIndex)
let length = range.startIndex.distanceTo(range.endIndex)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(16)], range: NSMakeRange(start, length))
self.setAttributedTitle(attr, forState: UIControlState.Normal)
}
}
func boldSubstring(substr: String) {
let range = substr.rangeOfString(substr)
if let r = range {
boldRange(r)
}
}
Anyone have anything?
Swift 4 version of chicobermuda's answer:
let text = "This is the"
let attr = NSMutableAttributedString(string: "\(text) button's text!")
attr.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(0, text.count))
cell.nameLabel.setAttributedTitle(attr, forState: .normal)
// "**This is the** button's text!"
it works fine