How to color text in UITextView - ios

I've got four buttons on the view controller and a text view. These five buttons has colors, for example red, yellow, green, blue and black.
When the user started to type without pressing those buttons the color of the text view being typed should have black color text. If user press red button then the color of the text from that point should be red until the user press any other colored button.
How to do this ? Ive followed this tutorial https://www.objc.io/issues/5-ios7/getting-to-know-textkit/
But do not know how to customized it to what I want to achieve.

Here is how I proceed if it can helps you:
1- add one property to retain current Color and initialize it with black color
#property (nonatomic, retain) UIColor *curColor;//in your interface declaration
self.curColor = [UIColor blackColor];//Init it in Viewdidload for example
2- implements UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSAttributedString *currentText = self.Textview.attributedText;//To store current text and its attributs
NSAttributedString *newOneText = [[NSAttributedString alloc] initWithString:text attributes:#{NSForegroundColorAttributeName:self.curColor}];//for the new text with selected color
NSMutableAttributedString *shouldDisplayText = [[NSMutableAttributedString alloc] initWithAttributedString: currentText];
[shouldDisplayText appendAttributedString: newOneText];// add old and new text
self.Textview.attributedText = shouldDisplayText;//set it ton control
return NO;
}
3- Add IBAction for changing color
=>
- (IBAction) redColorClicked
{
self.curColor = [UIColor colorWithRed:1.0f green: 0.0f blue:0.0f alpha:1.0f];
}
- (IBAction) blueColorClicked
{
self.curColor = [UIColor colorWithRed:0.0f green: 0.0f blue:1.0f alpha:1.0f];
}

You need to use NSAttributedString class.
let defaultAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize()),
NSForegroundColorAttributeName: UIColor.blackColor()]
let text = "this text is red and yellow"
let str = NSMutableAttributedString(string: text, attributes: defaultAttributes)
str.setAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: (text as NSString).rangeOfString("red"))
str.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: (text as NSString).rangeOfString("yellow"))
textView.attributedText = str

You can use NSMutableAttributedString to achieve that. The idea is the following (I didn't tested it, just wrote it here by hand):
NSString *str = #"stackoverflow";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
// Set foreground color of "stack" substring in our string to red
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor];
range:NSMakeRange(0, 5)];
Using this method you can achieve what you want applying color to ranges you want in the text.
You can set the attributed text to you UILabel like that:
yourLabel.attributedText = attributedString

Related

Change attributed text color with link IOS

How I can change the attributed text color from blue to white?
When I click on the UITextView the app opens the url, I just need to change the color to white.
My code is in C# but I think it can be converted to swift or objective-c easily.
I have tried this way but it didn't work:
NSMutableAttributedString footerText = new NSMutableAttributedString(myFooterText, new UIStringAttributes
{
ForegroundColor = UIColor.White,
Link = new NSUrl(myLinkString)
});
//Set footer text
MyTextView.AttributedText = footerText;
I fixed it by implementing normal text view with my custom text color and the underline, On user click I open the browser with my url.
Sample code snippet
UIStringAttributes attrHyperlink= new UIStringAttributes();
attrHyperlink.UnderlineStyle = NSUnderlineStyle.Single;
attrHyperlink.ForegroundColor = UIColor.Purple.CGColor;
NSMutableAttributedString attString = new NSMutableAttributedString(StringValue);
attString.AddAttributes(attrHyperlink, new NSRange(0,StringValue.Length));
MyTextView.AttributedText = attString;
Try this
Check this Attribute string for Link
NSString *str = #"Link";
NSMutableAttributedString *aStr = [[NSMutableAttributedString
alloc]initWithString:str attributes:nil];
[aStr addAttribute:NSLinkAttributeName value:#"Your Link here"
range:[str rangeOfString:#"Link"]];
[UITextView appearance].linkTextAttributes = #{ NSForegroundColorAttributeName : UIColor.redColor };
[self.text_View setAttributedText:aStr];
[self.text_View setTextAlignment:NSTextAlignmentNatural];
See the image attached i feel you want something like this. Use following code snippet. It is working on my end
self.infoTextView.text = #"I am text. I am link.";
NSString *info = self.infoTextView.text;
NSRange commaRange = [info rangeOfString:#"I am link."];
NSMutableAttributedString *infoString = [[NSMutableAttributedString alloc] initWithString:info];
[infoString addAttribute: NSLinkAttributeName value: #"http://www.google.com" range: commaRange];
self.infoTextView.tintColor = [UIColor colorWithRed:255.0f/255.0f green:181.0f/255.0f blue:51.0f/255.0f alpha:1.0]; //link color
[infoString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:61.0/255.0 green:82.0/225.0 blue:96.0/255.0 alpha:1.0] range:(NSRange){0, [info length]}]; //original text color
[infoString addAttribute:NSFontAttributeName value:self.infoTextView.font range:(NSRange){0, [info length]}];
self.infoTextView.attributedText = infoString;
The accepted answer is more of a workaround than a fix.
To change the link-color I used the code from Dhaval and changed it to Xamarin.iOS. Use the TintColor attribute like so:
var textColor = (Color)Element.GetValue(Label.TextColorProperty);
str.AddAttribute(UIStringAttributeKey.ForegroundColor, textColor.ToUIColor(Color.White), new NSRange(0, str.Length)); // Normal text color
str.AddAttribute(UIStringAttributeKey.Link, new NSUrl(item.Link), new NSRange(item.Start, item.Text.Length)); // Add a link.
}
Control.TintColor = textColor.ToUIColor(Color.Wheat); // The LINK color
Control.AttributedText = str;

How to make textLabel on UITableViewCell with multiple colours?

I am using UITableview for listing names of person and also implement UISearchbar for searching different names.I want to change textLabel color on UITableViewCell when user searching on specific item,for example when i am typing name “Ant” on searchbar,need to change color of “Ant” on UItableview. Please help me.
You need to look at using NSAttributedString to specify the colour of the text. You will need to process the visible cells on each change in the search criteria and check when configuring cells for display, find the search text in the name string and set the appropriate format attributes for the found range.
You can use below method to fulfil your requirement.
- (NSAttributedString *)highlightText:(NSString *)textToBeHighlighted inString:(NSString *)fullString {
NSDictionary *attributeForFullText = #{
NSForegroundColorAttributeName : [UIColor blackColor],
NSFontAttributeName : [UIFont systemFontOfSize:10.0f]
// And more......
};
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributeForFullText];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[fullString rangeOfString:textToBeHighlighted]];
/* you can use the above statement to do single style,
but if you want to do something more like size, font, alignment etc.
then you can do by below */
[attributedString addAttributes:dictionary_with_more_style range:[fullString rangeOfString:textToBeHighlighted]];
return attributedString;
}
And just call it from your cellForRowAtIndexPath
UILabel *titleLabel;
NSString *fullTitle;
NSString *searchString;
[titleLabel setAttributedText:[self highlightText:searchString inString:fullTitle];
You can make use of attributedText property of UILabel. This decorates the text on a label. Create a category for UITableViewCell and write a method and do the following:
#implementation UITableViewCell(asdf)
- (void)setText:(NSString *)text withMatchingText:(NSString *)matchingText;
{
// Set the default text color to the label text.
self.textLabel.textColor = // Default text color
if (matchingText.length > 0) {
// Create the color for the matching text.
UIColor *matchingColor = // Text color for the matching text, eg. "Ant"
//Find the range of the matching text from the whole text.
NSRange firstMatchingRange = [text rangeOfString:matchingText options:NSCaseInsensitiveSearch];
// Create an attributed string with matching color for your matching text on the whote text.
NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:text];
[mString addAttribute:NSForegroundColorAttributeName
value:matchingColor
range:firstMatchingRange];
self.textLabel.attributedText = mString;
}else {
self.textLabel.text = text;
}
}
In your viewController's tableView:cellForRowAtIndexPath: method do the following:
NSString *text = // the name property
cell setText:text withMatchingText:self.searchBar.text];
self.searchBar is the property of type UISearchBar you have on your ViewController connected with the search bar on your storyboard/xib.
The above code does like, If your search bar is having text then, It set the matchingColor to the matching text (eg. Ant) and the other letter(ony) will be the default colour. If no more matching text is there, then the whole text will be displayed with the default text colour.
This may help you.
Check this code. It may solve your problem.
Put this code in tableView:cellForRowAtIndexPath: method of your controller.
NSString *title = #"Test this answer";
NSString *searchText = #"ans";
NSMutableAttributedString *originalString = [[NSMutableAttributedString alloc] initWithString:title];
NSRange range = [title rangeOfString:searchText];
if (range.location == NSNotFound) {
NSLog(#"No match found");
}
else {
NSLog(#"Found the range of the substring at (%lu, %lu)", (unsigned long)range.location, range.location + range.length);
[originalString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
cell.lbl_Title.attributedText = originalString;

Keep the colors of the textView text after appending NSSting

I'm using the next method to change the colors of few words in textView:
+(void)changeColorToTextObject : (UITextView *)textView ToColor : (UIColor *)color FromLocation : (int)location length : (int)length
{
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: textView.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
[textView setAttributedText: text];
}
and it looks like this:
but when i'm adding new value to this text the color are gone.
myTextView.text = [myTextView.text stringByAppendingString:newStr];
And it looks like this:
How can I keep the colors like before with the new string?
Instead of myTextView.text = [myTextView.text stringByAppendingString:newStr]; use:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:myTextView.attributedText];
NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:newStr];
[text appendAttributedString:newAttrString];
myTextView.attributedText = text;
Your code does not work because you are assigning to a new string to the text property of myTextView. text is just just a NSString property and thus is not able to display colors or other things that can be displayed using an NSAttributedString.
Note that writing myTextView.attributedText = text; calls the setter of the property attributedText and thus is 100% equivalent to [myTextView setAttributedText:text];, just a different notation.

Multiple placeholder text color in iOS

Is it possible to have multiple color text in a placeholder?
For example
Write Text - I will prepend this.
"Write Text" will be black, while "I will prepend this." will be grey.
Multiple Textfiled placeholder in ios.
self.txt_First.attributedPlaceholder = [self String:#"Brewery (Sierra Nevada)" Range:7];
In above textfield first seven character is red and other are gray.
Use the below mehod for setting multiple color.
-(NSAttributedString *)String:(NSString *)str Range:(int )Rannge
{
NSMutableAttributedString *attString =
[[NSMutableAttributedString alloc]
initWithString:str];
[attString addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: NSMakeRange(0,Rannge)];
[attString addAttribute: NSForegroundColorAttributeName
value: [UIColor graycolor]
range: NSMakeRange(Rannge + 1,str.length - Rannge -1)];
return attString;
}
Multiple placeholder color Output :
I have Simple way for this .
Add UILabel in UITextField below and set UITextField clearColor .and set your UILabel text as you required and set that text color same as placeholder color .

Set NSAttributedString's background color in custom view's drawRect function

I want to draw text with background color in my custom view, but I found that if
I add NSBackgroundColorAttributeName attribute to my NSAttributedString , it doesn't appear.
when I remove background color attribute, it draws normaly :
-(void) drawRect : (CGRect)rect
{
NSAttributedString *test = [[NSAttributedString alloc]initWithString:#"test"
attributes: #{NSForegroundColorAttributedName:[UIColor whiteColor],
NSBackgroundColorAttributeName:[UIColor blackColor]}];
[test drawAtPoint:CGPointMake(0,0)];
}
But if I add a label on my custom view, and modify its attributed text, It will work:
NSMutableAttributedString *attributedText = [self.testLabel.attributedText mutableCopy];
NSString *str = [attributedText string];
NSRange r = [str rangeOfString:str];
[attributedText addAttributes: #{NSForegroundColorAttributedName:[UIColor whiteColor],
NSBackgroundColorAttributeName:[UIColor blackColor]} range:r];
self.testLabel.attributedText = arrtibutedText;
why is that ?

Resources