My app will display some text, and I want to make the hyper-link be able to be clicked. I have some questions about this feature.
How do I parse the text to be aware this is a link?
Once a user click the link, I don't want the OS to switch to Safari and open the link, this is very bad because the user can not go back to my application. So I want to open the link within my application. As soon as the user click the link, my app will present a view modally to display the web content. Any advice would be appreciated.
You probably want to subclass UILabel. When you change the text, have it try to see if the text is a hyperlink, if it is, set it to enable user interaction and change the text color to blue. When the user taps on the link, send a message to the main view controller (Possibly through delegation) to open the link.
to display web content in your app, look into UIWebView.
If your text can be formatted as html with hyperlinks (<a> tags), you could use a UIWebView to display it.
The UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method is called when a user taps a link. Usually you would make your controller implement this method, and set the UIWebView's delegate to the controller.
You're going to want to check out a Github project called LRLinkableLabel.
It will auto-detect any URLs that are inside the .text property.
You can use it like so:
LRLinkableLabel *label = [[LRLinkableLabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 20.0)];
label.delegate = self;
label.text = #"Check out http://dundermifflin.com to find some great paper deals!";
Then just make sure self implements this method:
- (void) linkableLabel:(LRLinkableLabel *)label clickedButton:(UIButton *)button forURL:(NSURL *)url {
[[UIApplication sharedApplication] openURL:url];
}
You can also use the linkColor and textColor properties to configure the appearance of the label. From this point you can use it just like any other UILabel.
Remember to set the delegate to nil when you're all done to make sure everything is all cleaned up.
Hope this helps.
Related
I have a UILabel whose text I am getting from a server. Some of the text is to be identified as links, and on touching those links some action should be performed. e.g.
NSString *str = #"My phone number is 645-345-2345 and my address is xyz";
This is the complete text for UILabel. I have only one UILabel for displaying this text (Text is dynamic. I just gave an example.). On clicking these links I need to perform actions like navigating to some different screen or make a call.
I know that I can display such text with help of OHAttributedLabel. And the links can be displayed as follows :
[label1 addCustomLink:[NSURL URLWithString:#"http://www.foodreporter.net"] inRange:[txt rangeOfString:someString]];
But I wonder how can I make these text links perform some action like navigation to different screen or making a call.
Let me know if more explanation is required.
You can add custom actions to any of the available UILabel replacements that support links using a fake URL scheme that you'll intercept later:
TTTAttributedLabel *tttLabel = <# create the label here #>;
NSString *labelText = #"Lost? Learn more.";
tttLabel.text = labelText;
NSRange r = [labelText rangeOfString:#"Learn more"];
[tttLabel addLinkToURL:[NSURL URLWithString:#"action://show-help"] withRange:r];
Then, in your TTTAttributedLabelDelegate:
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([[url scheme] hasPrefix:#"action"]) {
if ([[url host] hasPrefix:#"show-help"]) {
/* load help screen */
} else if ([[url host] hasPrefix:#"show-settings"]) {
/* load settings screen */
}
} else {
/* deal with http links here */
}
}
TTTAttributedLabel is a fork of OHAttributedLabel.
If you want a more complex approach, have a look to Nimbus Attributed Label. It support custom links out-of-the-box.
You can use UITextView with Phone numbers and links detection YES, scrolling disabled YES user interaction enabled YES, instead of UILabel.
My project has successfully used OHAttributedLabel for this. Check out the
-(BOOL)attributedLabel:(OHAttributedLabel*)attributedLabel shouldFollowLink:(NSTextCheckingResult*)linkInfo;
method in OHAttributedLabelDelegate (link). It allows you to decide what happens when a link is clicked. If you look at the source for the example from the OHAttributedLabel project, it's used to display an alert. If you returned NO in this case (to keep the default action from happening too), you could just do whatever you wanted like navigation, etc.
Note however that this requires that you can determine the action correctly just from the text. For our project, we used a slightly fancier solution, where the server sent us text with tags in them and a list of commands to perform for each tag.
There a project called FancyLabel that is about what you need. It might need some customization though.
Also, I think Three20 has this functionality, but it might be an overkill if you don't already use it.
There's also a much simpler solution, if all of your links are phones \ addresses \ urls. You can simply use a UITextView instead of a UILabel. It has auto detection of phones, address, etc. (just check the boxes in IB)
You can also have custom actions in response to click events on those links by overriding openURL, as explained here
Is there a specific reason that you must use a UILabel instead of a UITextView?
Note that a lot of the implementations of attributed labels inherit from UIView or don't implement all of UILabel's functionality.
You can use custom button to give a look like of link ..Also you can add gesture on the custom label if you dont want to use button ..
UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(userTappedOnLink:)];
// if labelView is not set userInteractionEnabled, you must do so
[labelView setUserInteractionEnabled:YES];
[labelView addGestureRecognizer:gesture];
I'm not a fan of being forced to use UITextView or a third party lib when all I need is a lightweight label that renders links (and that tells me when they're tapped!)
Here's my attempt at a lightweight UILabel subclass able to detect link taps. The approach is different from others I've seen in that it gains access to the UILabel's shared NSLayoutManager via a delegate callback added to NSTextStorage via a category extension. The beauty is that UILabel performs its native layout and drawing - other UILabel replacements often augment or replace the native behavior with an additional NSLayoutManager/NSTextContainer.
Probably App Store safe, but somewhat fragile - use at your own risk!
https://github.com/TomSwift/TSLabel
I have a label on which I want to ensure that when user clicks the label, it opens a hyperlink attached with it in a webview.
Label and its hyperlink are fetched from an SQLite database.
Can you please let me know how to do that?
Give IBAction on your custome button
-(IBAction) goToLink
{
NSString *Links_name = #"Your link";
NSLog(#"Link : %#",Links_name);
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:Links_name]];
}
You can't since you can't pass an action event with Label.
So, for this you need to use Custom Button
or either the TextView using detection property of TextView.
USing of Custom Button is much easy then using TextView.
hope that will work... :)
I have never use youtube api in iPhone ...I tried to use GData but was missed in some steps here are link ans tutorial ....So never implemented it...
Due to which i used RSS feed and load it on tableView ...
and when user click on any row then the actual webPage opens in WebView and user have to click on the video to run it....
But now i don't want this ....
Can anyone provide me a better solution....
Thanks...
As I have given a brief answer here
I am explaining it in detail:
Put a button of same size and without any background image over your webview.
When the user presses this button open a new modal view with only a full screen size webview in it.
Pass the same html string to load the webview (that you were passing in your smaller webview).
Pass the touches programmatically to the webview like:
– (void) touchTheWebViewProgrammatically{
for(UIView* vw in [webView subviews]){
if([vw isKindOfClass:[UIButton Class]])
[vw sendActionsForControlEvents:UIControlEventAllEvents];
}
}
In my app i want to put my website's url on home screen and on clicking on it i want it to be open as a WebView.
How should i go for this.
Thanks,
Previous commenter is incorrect. You can open any hyperlink either externally with Safari or internally with a UIWebView.
Add a UIWebViewController to your project. Then, instantiate an instance of a the UIWebViewController that will be shown inside your app--you'll do this by declaring a property & synthesizing it within your main view controller (which will need to be declared as a UIWebViewDelegate), such as:
#interface MyMainViewController: UIViewController <UIWebViewDelegate> {
// Your implementation code here
}
When a user taps the button (assuming you make it a button, rather than just a text hyperlink), you instruct your app to add the UIWebView to the view stack, loading the correct link. You'll want to either do this within a modal view or within a navigation stack so your users can get back out of the web view, of course.
In your MyMainViewController implementation file, something like this:
-(void) showWebView {
// NOTE: I have not tested this, just prototyping
// off the top of my head
UIWebView *myWebView = [[UIWebView alloc] init];
myWebView.delegate = self;
NSURL *homeUrl = [[NSURL alloc] initWithString:#"http://example.com"];
NSURLRequest *homeRequest = [NSURLRequest requestWithURL:homeURL];
[myWebView loadRequest:homeRequest];
[self.presentModalViewController: myWebView animated:YES];
// Don't forget to release objects when you're done
[myWebView release]; // etc.
}
Now, this is off the top of my head from what I know and have done. But I hope you get the general idea. I offer no warranty of any kind here, but do guarantee this is entirely possible with minimal headache. If you get stuck, check out the developer references for UIWebView. Apple's docs are top-notch & show great examples to get you up and running quickly.
Best.
I am working on an iPhone app, and would like to be able to click on a link that is in UITableView. When the Link, and only the link is selected I want the Safari app to be opened to the selected link. Any suggestions on how to do this? Thanks so much!
There are multiple solutions to your problem.
If the links are the only object in the cell, then you could just make call the didSelectRowAtIndexPath:(NSIndexPath *)indexPath function of UITableView to gather the link from your array of table data, and then use
[[UIApplication sharedApplication] openURL:myURL];
to open the URL.
Alternatively you could create your own UITableCell subclass that contains a custom button (instead of a rounded rect button) that has no image or background (only text) so that it has the appearance of a link (you could even color the text blue, and underline it...). When the user clicks the button, your handler function would then call the same openURL function as above.
The above method works best if you have multiple items in each cell (which is why you would have to create a custom cell...
A naive approach would be to embed a tiny UIWebView into each cell. UIWebView has a delegate that lets you know when a link is clicked which you can implement to launch the Safari or navigate to a new controller hosting a full screen UIWebView.
This approach might be too resource intensive and I haven't tried it myself but if it does work it would offer a lot of flexibility. Would love to know the results if you try it.
To launch a link in safari use:
NSURL *url = [NSURL URLWithString:#"http://stackoverflow.com"];
if (![[UIApplication sharedApplication] openURL:url]) {
NSLog(#"%#%#", #"Failed to open url:", [url description]);
}
Is the link in its own row in the UITableView? If so, then you can handle it within didSelectRowAtIndexPath when the appropriate row is clicked.