Change attributed text color with link IOS - 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;

Related

How to color text in UITextView

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

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.

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 ?

Attribute for Multiple Text

I have this code and it's working (answer from https://stackoverflow.com/a/3586943/1187014), but I want try modify it a little bit :
NSString *text = #"Forgot password?";
if ([_labelForgotPassword respondsToSelector:#selector(setAttributedText:)])
{
// iOS6 and above : Use NSAttributedStrings
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
UIColor *foregroundColor = [UIColor whiteColor];
// Create the attributes
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
boldFont, NSFontAttributeName,
foregroundColor, NSForegroundColorAttributeName, nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
regularFont, NSFontAttributeName, nil];
const NSRange range = NSMakeRange(16,0);
// Create the attributed string (text + attributes)
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
// Set it in our UILabel and we are done!
[_labelForgotPassword setAttributedText:attributedText];
} else {
// iOS5 and below
// Here we have some options too. The first one is to do something
// less fancy and show it just as plain text without attributes.
// The second is to use CoreText and get similar results with a bit
// more of code. Interested people please look down the old answer.
// Now I am just being lazy so :p
[_labelForgotPassword setText:text];
}
What if I have multiple text, let's say :
NSString *text1 = #"Forgot password?"; // relates with UILabel _labelForgotPassword
NSString *text2 = #"I agree with terms and condition"; // relates with UILabel _labelTerms
NSString *text3 = #"Your country is not listed yet?"; // relates with UILabel _labelCountry
First method that came into my mind is by having nested IF, but nested IF will be very ugly when I have lots of text which need to be attributed, right?
So, how to create that code into a method so that I can just supply the string, name of _label, range, etc and return the result to specific UILabel. and it's all triggered under viewDidLoad. Not by button pressed, or something else.
thank you.
What i am understanding is you want the same attributed logic to be applied to all labels. You can create a category on UILabel if you want to use it for only UILabels.
Syntax of the category should be something like this:
+(NSMutableAttributedString *) convertToAttributedText: (NSString *) text withFont: (UIFont *) font
{
// write the above logic here
//return the attributed text;
}
You can pass the text1 / text2 / text3 whatever to this api and you will get the attributed text.
label.attributedtext = [NSString convertToAttributedText: text withFont:font];
You can configure this API parameters based on your need.
Hope this helps.

Letterpress effect for UILabel in iOS 7 SDK

In the WWDC 2013 videos they show that a developer can use a letterpress effect on text.
Does anyone have any example code of how to do this/how to do this with a UILabel?
They've made it pretty simple now.
//Use any font you want or skip defining it
UIFont* font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
//Use any color you want or skip defining it
UIColor* textColor = [UIColor blueColor];
NSDictionary *attrs = #{ NSForegroundColorAttributeName : textColor,
NSFontAttributeName : font,
NSTextEffectAttributeName : NSTextEffectLetterpressStyle};
NSAttributedString* attrString = [[NSAttributedString alloc]
initWithString:note.title
attributes:attrs];
myTextLabel.attributedText = attrString;
It's part of NSAttributedString UIKitAdditions

Resources