How to highlight search string in AutoComplete results for IOS5? - objective-c

Google autocomplete would bolden what we search
For example: If we search for hell we'll see "hell o"
I think I need attributed string, so my code is:
- (NSMutableAttributedString*) highlightSearchString:(NSString*)substringToHighlight{
NSMutableAttributedString * mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:self];
NSUInteger count = 0, length = [mutableAttributedString length];
NSRange range = NSMakeRange(0, length);
count = 0,
length = [mutableAttributedString length];
range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[mutableAttributedString string] rangeOfString:substringToHighlight options:0 range:range];
if(range.location != NSNotFound) {
//[mutableAttributedString setTextColor:[UIColor blueColor] range:NSMakeRange(range.location, [word length])];
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSDictionary * dict = #{NSFontAttributeName:boldFontName};
NSRange rangeHighlight = NSMakeRange(range.location, substringToHighlight.length);
[mutableAttributedString setAttributes:dict range:rangeHighlight];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return mutableAttributedString;
}
But it doesn't work because NSFontAttributeName is available only in iOS6.
After that I need to update the tableViewCell
cell.textLabel.text=text;
with something that take advantage of the atributed text.

Just use the CoreText definition for the font:
UIFont *font = [UIFont boldSystemFontOfSize:12];
CTFontRef ctFontRef = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
NSDictionary * dict = #{(NSString *)kCTFontAttributeName : (__bridge id) ctFontRef};
For the seconds problem:
The default UILabel in the iOS SDK only supports NSAttributedString from iOS 6. Thus in
iOS 5 you will either have to draw the NSAttributedString your self using CoreText of get some third part label that does support NSAttributedString like: TTTAttributedLabel.

Related

Setting UILabel with multiple font color at drawatpoint

How to set the multiple font color in UIlabel drawatpoint.
I tried using below code to change the font attribute but I have no idea how to set a NSMutableAttributedString to this since it only accepts NSDictionary
[self.textColor setFill];
[self.text drawAtPoint:rect2.origin withAttributes:attrName];
We use this to set the attribute
NSMutableAttributedString *attrsString =
[[NSMutableAttributedString alloc]
initWithAttributedString:"String1/String2"];
// search for word occurrence
NSRange prange = [lbl.text rangeOfString:#"String1"];
NSRange lrange = [lbl.text rangeOfString:#"String2"];
if (prange.location != NSNotFound) {
[attrsString addAttributes:attributeGreen range:prange];
[attrsString addAttributes:attributeRed range:lrange];
}
lbl.attributedText = attrsString;
Originally we use this in the UILabel subclass - this subclass is used to resize the text.
[self.textColor setFill];
[self.text drawAtPoint:rect2.origin withFont:tmpfont];
I expect to have String1 in green font and String 2 in red font
Add a font attribute with font size.
NSString *string = #"String1/String2";
NSMutableAttributedString *attrsString =
[[NSMutableAttributedString alloc]
initWithAttributedString:#"String1/String2"];
// search for word occurrence
NSRange prange = [lbl.text rangeOfString:#"String1"];
NSRange lrange = [lbl.text rangeOfString:#"String2"];
//Setting font
[attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, string.length)];
if (prange.location != NSNotFound) {
[attrsString addAttribute: NSForegroundColorAttributeName value: [UIColor greenColor] range:prange];
}
if (lrange.location != NSNotFound) {
[attrsString addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range:lrange];
}
lbl.attributedText = attrsString;

Count and change text color of occurrences of string in NSTextView

I have an task where I need to count the occurrences of errors in a log file and I know how to do that. Now Im trying to change the font color of these occurrences. I have it kinda working but it doesn't change the whole word to the wanted color and for the next occurrence of that string it shifts over 3 characters.
See image below.
I searched for the word "Checked" and it gave me these results.
Below is the code that I am using
NSArray * lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
wordresult = [lines componentsJoinedByString:#""];
if (occS2 == 1)
{
NSString * box2 = [_occSearchTwoTextBox stringValue];
NSUInteger countFatal = 0, length4 = [wordresult length];
NSRange range4 = NSMakeRange(0, length4);
while(range4.location != NSNotFound)
{
range4 = [wordresult rangeOfString: box2 options:NSCaseInsensitiveSearch range:range4];
[self.stringLogTextView setTextColor:[NSColor redColor] range:range4];
NSLog(#"Occurance Edited");
if(range4.location != NSNotFound)
{
range4 = NSMakeRange(range4.location + range4.length, length4 - (range4.location + range4.length));
countFatal++;
}
}
NSString * FatalCount = [NSString stringWithFormat:#"%lu", (unsigned long)countFatal];
[_customSearchTwoTextBox setStringValue:FatalCount];
}
Can anyone please point me to where to why its shifting? I can only assume that it has something to do with my range but I'm not sure what to do to resolve.
Thanks for everyones time!
I'm not sure why your method isn't working correctly, but I would do it a different way. Using enumerateSubstringsInRange:options:usingBlock:, you can enumerate your string by word, and get the range of each word passed in to the method for you. If the word is "Checked", you can increment your count and also set the attributes for that range of a mutable attributed string. Here is an example of how to use that method,
NSString *theText = #"] Tables initialized\n]Database version Checked\n]Got login id-1\n] Tables initialized\n]Database version Checked\n]Got login id-1\n] Tables initialized\n]Database version Checked\n]Got login id-1\n";
NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc] initWithString:theText];
NSDictionary *dict = #{NSForegroundColorAttributeName:[NSColor greenColor]};
__block int count = 0;
[theText enumerateSubstringsInRange:NSMakeRange(0, theText.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring isEqualToString:#"Checked"]) {
[attrib setAttributes:dict range:substringRange];
count ++;
};
}];
self.textView.textStorage.attributedString = attrib;
NSLog(#"count is: %d",count);

How to change background only to some words in a textView

I need to change the background color of some particular words in a text that stay in a textView. Something similar to what happens in Firefox when you seearch for a word... So lets say I have a textView with this text
"A man is sitting in front of my porch and another man is calling him"
and I want to change background color to the 2 occurence of the word
"man"
... how could I do that?
I know that there is NSAttributedString to do this kind of things but I can not understand how to modify only some particular words... in the examples I found Googling it there were only examples of how to change the first 5 characters or things like this...
Try this:
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: #"Your String"];
NSUInteger count = 0;
NSUInteger length = [attrString length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[attrString string] rangeOfString:#"YOURWORD" options:0 range:range];
if(range.location != NSNotFound) {
[attrString addAttribute:NSBackgroundColorAttributeName value:YOURCOLOR range:NSMakeRange(range.location, [word length])];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}

Custom NSFormatter in Objective C

I am trying to write my own custom formatter in Objective C by subclassing NSNumberFormatter. Specifically what I'd like to do is make a number turn red if it is above or below certain values. The apple documentation says
For example, if you want negative financial amounts to appear in red, you have this method return a string with an attribute of red text. In attributedStringForObjectValue:withDefaultAttributes: get the non-attributed string by invoking stringForObjectValue: and then apply the proper attributes to that string.
Based on this advice I implemented the following code
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[self stringForObjectValue:anObject]];
if ([[attrString string] floatValue] < -20.0f) {
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, 10)];
return attrString;
} else return attrString;
}
But when I test this all it does is freeze my application. Any advice would be appreciated. Thanks.
I believe this has something to do with your NSRange that you create. I believe your length (10 in your example) is out of bounds. Try getting the length of the string that you use to initialize your NSMutableAttributedString.
For example:
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < -20.0f)
{
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, stringLength)];
}
return attrString;
}
Here is how I was finally able to implement this. To make it more visible when a number is negative, I decided to make the background of the text red with white text. The following code does work in a NSTextField cell. I'm not sure why the code in my question (and the answer) does not work, addAttribute should work.
- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes: (NSDictionary *)attributes{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < 0)
{
NSDictionary *firstAttributes = #{NSForegroundColorAttributeName: [NSColor whiteColor],
NSBackgroundColorAttributeName: [NSColor blueColor]};
[attrString setAttributes:firstAttributes range:NSMakeRange(0, stringLength)];
}
return attrString;
}

Any way to bold part of a NSString?

Is there any way to bold only part of a string?
For example:
Approximate Distance: 120m away
Thanks!
What you could do is use an NSAttributedString.
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
//draw attrString here...
Take a look at this handy dandy guide to drawing NSAttributedString objects with Core Text.
As Jacob mentioned, you probably want to use an NSAttributedString or an NSMutableAttributedString. The following is one example of how you might do this.
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"Approximate Distance: 120m away"];
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[NSFont fontWithName:#"Helvetica-Bold" size:12.0]
range:selectedRange];
[string endEditing];
If you do not want to bother with fonts (as not every variation of font contains "Bold"), here is another way to do this. Please be aware, this is currently only available on OS X...:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"];
[attrString beginEditing];
[attrString applyFontTraits:NSBoldFontMask
range:NSMakeRange(22, 4)];
[attrString endEditing];
The code above gave me crash when I created UILabel with this attributedString.
I used this code and it worked:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSRange boldedRange = NSMakeRange(0, 1);
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:#"Lato-Bold" size:12];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];
Swift
Also includes getting the range of the string you want to embolden dynamically
let nameString = "Magoo"
let string = "Hello my name is \(nameString)"
let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
let nsString = NSString(string: string)
let range = nsString.rangeOfString(nameString)
if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }
someLabel.attributedText = attributedString
To bold a string without hardcoding its font, you can use the StrokeWidth attribute with a negative value:
let s = NSMutableAttributedString(string: "Approximate Distance: 120m away")
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26))
An NSString is just a data container. It doesn't contain any details about presentation concerns.
It sounds like what you probably want to do is bold part of the UILabel that is being used to display your string. Which I don't think you can do. But you could always break the UI down into three labels, one for "Approximate Distance:", one for "120 m", and one for "away". Place them in-line with each other and you should get the desired effect.
Another option might be to use a UIWebView and a little bit of markup to display your string with embedded formatting information, as discussed here:
http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview
In Xamarin ios you can bold part of a NSString this way:
public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange)
{
var firstAttributes = new UIStringAttributes {
Font = UIFont.BoldSystemFontOfSize(fontSize)
};
NSMutableAttributedString boldString = new NSMutableAttributedString (str);
boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange));
return boldString;
}
and call this method:
myLabel = new UILabel ();
...
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);
I coupled #Jacob Relkin and #Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:
UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = #"Approximate Distance: 120m away";
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFont
range:boldedRange];
[attrString endEditing];
I took a look at the official documentation: 1 and 2.
Shorter way using Swift5+
let labelNotes = UILabel() //or UITextView(), etc...
let attributedNotes = NSMutableAttributedString(string: "Bold: some stuff not bold")
attributedNotes.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSRange(location: 0, length: 5))
labelNotes.attributedText = attributedNotes
If you don't want to hardcode the font or/and the size try this code for bolding full strings:
NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:mainString];
[myString beginEditing];
[myString addAttribute:NSStrokeWidthAttributeName
value:[[NSNumber alloc] initWithInt: -3.f]
range:NSMakeRange(0, [mainString length])];
[myString endEditing];