Skip to content

Instantly share code, notes, and snippets.

@benvium
Created November 29, 2012 13:21
Show Gist options
  • Save benvium/4169018 to your computer and use it in GitHub Desktop.
Save benvium/4169018 to your computer and use it in GitHub Desktop.
Adding and catching links in a UILabel on iOS5 when you're designing with Interface Builder / Storyboards.
#import "TTTAttributedLabel.h"
@interface CVSignupViewController : UITableViewController <TTTAttributedLabelDelegate> {
IBOutlet TTTAttributedLabel* _legalLabel;
}
@end
#import "CVSignupViewController.h"
// you MUST add this import.!
#import <CoreText/CoreText.h>
@interface CVSignupViewController ()
@end
@implementation CVSignupViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Colors etc for links (default hideous blue)
_legalLabel.linkAttributes = @{
(NSString*)kCTForegroundColorAttributeName : (id)[UIColor grayColor].CGColor,
(NSString *)kCTUnderlineStyleAttributeName : @YES
};
_legalLabel.activeLinkAttributes = @{
(NSString*)kCTForegroundColorAttributeName : (id)[UIColor blackColor].CGColor,
(NSString *)kCTUnderlineStyleAttributeName : @YES
};
// If you've set the text in Interface Builder TTTAttributedLabel will crash unless you insert this line (!)
_legalLabel.text = _legalLabel.text;
NSRange r = [_legalLabel.text rangeOfString:@"Privacy Policy"];
[_legalLabel addLinkToURL:[NSURL URLWithString:@"action://privacyUrl"] withRange:r];
r = [_legalLabel.text rangeOfString:@"Terms of Use"];
[_legalLabel addLinkToURL:[NSURL URLWithString:@"action://termsUrl"] withRange:r];
[_legalLabel setDelegate:self];
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([[url scheme] hasPrefix:@"action"]) {
if ([[url host] hasPrefix:@"privacyUrl"]) {
// You clicked the privacy button!
} else if ([[url host] hasPrefix:@"termsUrl"]) {
// You clicked the terms button!
}
}
}
@end
@benvium
Copy link
Author

benvium commented Nov 29, 2012

Steps to get started:
Add TTTAttributedLabel (https://github.com/mattt/TTTAttributedLabel)

  • Use above code as basis for your UIViewController
  • Create a UILabel in IB/Storyboard (on UIViewController with Custom Class CVSignupViewController)
  • Add PLAIN text (e.g. Have a look at our Privacy Policy and Terms of Use)
  • Set the Custom Class to TTTAttributedLabel
  • Link the Label to the TTTAttributedLabel IBOutlet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment