UITextView Not Opening URL When Clicked - ios

I have a UITextView that has an attributed string inside, which contains a URL. The attributed string is being converted to a link, but when you press the link you get an error:
Unknown DDResult category 1 for result ; could not find any actions for URL www.myurl.com
Here is my code:
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(#"My Text", nil)];
NSRange range = [str.mutableString rangeOfString:#"www.myurl.com" options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"CourierPrime-Bold" size:15] range:NSMakeRange(0, range.location)];
[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:#"www.myurl.com"] range:range];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}
self.welcomeText.editable = NO;
self.welcomeText.attributedText = str;
//As a note, I have tried this with the value 0 and UIDataDetectorTypeLink
//and neither option worked.
self.welcomeText.dataDetectorTypes = UIDataDetectorTypeAll;
I am using an XIB and in the behavior options I have selectable enabled, and in the detection options I have links selected.
I would like for the link to be opened in the phones mobile browser if possible, rather than creating a webview.

The URL needs a scheme.
This:
[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:#"www.myurl.com"] range:range];
needs to be:
[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:#"http://www.myurl.com"] range:range];

In Swift :
The URL needs to be Secure (https)
IOS doesn't allow you to redirect the user to non secure links , so provide links with https
and to make a specific string clickable in UITextView using Swift
you can do as follow :
let link = "https://www.google.com"
let range = (text as NSString).range(of: link)
attribute.addAttributes([NSAttributedStringKey.link: link], range: range)

Related

Find last line of multiline label and change colour [duplicate]

This question already has answers here:
UILabel Text with Multiple Font Colors
(8 answers)
Closed 4 years ago.
I m working on multi line text with different colour.The following code to change the first line colour But want to change the last line colour.
NSRange rangeOfNewLine = [label.text rangeOfString:#"\n"];
NSRange newRange = NSMakeRange(0, rangeOfNewLine.location);
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:newRange];
NSArray* lines = [label.text componentsSeparatedByString:#"\n"];
NSString* lastLine = lines.lastObject;
NSRange rangeOfLastLine = [label.text rangeOfString:lastLine];
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:rangeOfLastLine];
//NSString *myString = #"I have to replace text 'Dr Andrew Murphy, John Smith' ";
NSString *myString = #"Not a member?signin";
//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];
//Fing range of the string you want to change colour
attributeText _label.attributedText = attString;
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:#"signin"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range];
//Add it to the label - notice its not text property but it's
attributeText _label.attributedText = attString;

Underline in attributed text not working in iPhone 6+

I want to create a method that returns me attributed text.
here is the code that i am using
- (NSAttributedString *)getUnderlineAttributedStringForText:(NSString *)strWholeString andTextToHaveLink:(NSString *)strLink TextColor:(UIColor *)textColor LinkColor:(UIColor *)linkColor withFont:(UIFont*)font {
NSRange stringRange = NSMakeRange(0, strWholeString.length);
NSRange linkRange = [strWholeString rangeOfString:strLink];
NSLog(#"String Link :: %#",[strWholeString substringWithRange:linkRange]);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strWholeString];
// Paragraph Style
NSMutableParagraphStyle *paragrapStyle = NSMutableParagraphStyle.new;
paragrapStyle.alignment = NSTextAlignmentLeft;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:stringRange];
[attributedString addAttribute:NSForegroundColorAttributeName value:textColor range:stringRange];
[attributedString addAttribute:NSFontAttributeName value:font range:stringRange];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range:linkRange];
[attributedString addAttribute:NSForegroundColorAttributeName value:linkColor range:linkRange];
return attributedString;
}
// This is how I call the method
[btnTermOfUse setAttributedTitle:[self getUnderlineAttributedStringForText:#"By signing up you agree to the Terms of Use" andTextToHaveLink:#"Terms of Use" TextColor:[UIColor darkGrayColor] LinkColor:[UIColor orangeColor] withFont:[UIFont systemFontOfSize:16]] forState:UIControlStateNormal];
This code works fine in all device except 6+.
Edits
- in 6+ just underline is not showing text colour change for the link text.
I can see the underline in iPhone 6 or 5S.
Any one have any idea regarding this?
I know there are already so many questions related to this but they didn't help me so I am writing here.
Found a hack !! :(
you should write this line before setting up the text,
[btnTermOfUse titleLabel].numberOfLines = 0;
This will show you the line on device too.

Display edited NSString in order

I have been working on this for a few days with help from this great community.
I have a NSArray that I need to edit NSStrings within. I have managed to detect a marker in the string and make it bold. However now I am trying to display the strings in the order that they are within the NSArray whilst maintaining the Bold that was added to the specific strings.
I can display the individual Bold String 'string' but I need it to be in order that it is within the array. I know of stringByAppendingString but this would put it at the end.
Any directions would be brilliant.
for (NSString *testWord in legislationArray) {
if ([testWord rangeOfString:#"BOLDME"].location != NSNotFound) {
//Remove Marker
NSString *stripped = [testWord stringByReplacingOccurrencesOfString:#"BOLDME" withString:#""];
//Get string and add bold
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped];
NSRange selectedRange = [stripped rangeOfString:(stripped)];
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Helvetica-Bold" size:18.0]
range:selectedRange];
[string endEditing];
//Where to go now with string?
}
}
cell.dynamicLabel.text = [legislationArray componentsJoinedByString:#"\n"];
EDIT
Based on the answers below I got it working however the bold method invokes this error:
componentsJoinedByString return a NSString, when you want a NSAttributedString.
Plus, you're setting your text to a receiver that awaits a NSString (cell.dynamicLabel.text), where what you want should be cell.dynamicLabel.attributedText.
Since there is no equivalent to componentsJoinedByString for a NSAttributedString return, you have to do it the oldway, with a for loop, starting with initializing a NSMutableAttributedString, and adding to it each components (that you may "transform") to it.
Here is a example and related question.
Just use additional array. Change your code to
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] init];
for (NSString *testWord in legislationArray) {
if ([testWord rangeOfString:#"BOLDME"].location != NSNotFound) {
//Remove Marker
NSString *stripped = [testWord stringByReplacingOccurrencesOfString:#"BOLDME" withString:#""];
//Get string and add bold
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped];
NSRange selectedRange = [stripped rangeOfString:(stripped)];
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Helvetica-Bold" size:18.0]
range:selectedRange];
[string endEditing];
//Where to go now with string?
[attrString appendAttributedString:string];
}
else
{
[attrString appendAttributedString:[[NSAttributedString alloc] initWithString:testWord]];
}
// NEW LINE
[attrString appendAttributedString:[[NSAttributedString alloc] initWithString:#"\n"]];
}
cell.dynamicLabel.attributedText = attrString;
UPDATE:
Your additional issue is not a error - this is a way how XCode shows attributed strings in debug window:

How to show multiple line text that has different font without using multiple Labels

I have to show a text paragraph that contains few words in bold font. ex.
If I use different labels then on changing the orientation it does not resize properly.
Can anyone tell me what can the best way to do it.
You can use an UITextView using NSAttributedString (have a look to the apple doc)
And you have an explanation of how to use it here.
You can find the range of your word and change the font or the color or whatever using :
- (IBAction)colorWord:(id)sender {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words = [self.text.text componentsSeparatedByString:#" "];
for (NSString *word in words)
{
if ([word hasPrefix:#"#"])
{
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
}
[self.text setAttributedText:string];
}
You have to use a NSAttributedString and assign it to the UITextField, this is an example:
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
[myAttributedString addAttribute:NSFontAttributeName
value:boldFont
range:NSMakeRange(0, 2)];
[myAttributedString addAttribute:NSFontAttributeName
value:regularFont
range:NSMakeRange(3, 5)];
[self.description setAttributedText:myAttributedString];
Find all the doc here:
NSAttributedString
For your case, you can use a webView and load it with your string:
[webView loadHTMLString:[NSString stringWithFormat:#"<html><body style=\"background-color: transparent;\">This is <b><i>Test</b></i> dummy text ..</body></html>"] baseURL:nil];

NSMutableAttributedString crashes when changing fonts for different ranges

So I'm trying to change the colors of a NSMutableAttributedString but I keep getting an out of bounds exception error when I try to add multiple ranges (see below). If on the other hand I just do a single range from 0 to totalLength-1, there is no issue. I don't know why this is happening.
My code is below:
NSString *testString = #"This is my test string for this example";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc] initWithString:testString];
int totalLength = [playerTurnString length];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor] range:NSMakeRange(0, 11)];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor] range:NSMakeRange(12, totalLength-1)];
An NSRange is a location and a length, so when you do
NSMakeRange(12, totalLength-1)
Your length is 12 too long and therefore exceeds the range of the string. You're trying to use it as a start and end location but that isn't how it works.

Resources