In many times a have needed a UILable with clickable content links, but this control doesn’t exists in Objective C. With the custom class that we will write, we can include this feature in our next project.
This custom control is really easy. First of all, we need to make a class from a UITextView, and then we will the control doesn’t editable, drop the borders and then assign the property to autodetect the diferent types of data (url, telephone number,…)
We can configure the color of the url text and the edgeInsets to simulate the appearance to the UILabel.
And thats all, this is the code to create the custom control.
//
// UILabelClickable.h
//
// Created by Unocerouno on 25/4/15.
//
#import <UIKit/UIKit.h>
@interface UILabelClickable : UITextView
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
//
// UILableClickable.m
//
// Created by Unocerouno on 25/4/15.
//
#import "UILabelClickable.h"
@implementation UILabelClickable
- (id)initWithFrame☹CGRect)frame{
self = [super initWithFrame:frame];
[self setUp];
return self;
}
- (id)initWithCoder☹NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
[self setUp];
return self;
}
-(void)setUp
{
[self setTextContainerInset:UIEdgeInsetsMake(0, 0.0f, 0, 0)];
self.textContainer.lineFragmentPadding = 0;
self.layer.borderWidth = 0;
self.editable = NO;
self.scrollEnabled = NO;
self.dataDetectorTypes = UIDataDetectorTypeAll;
self.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0 green:0.58 blue:0.835 alpha:1], NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle]};
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
size.width += self.edgeInsets.left + self.edgeInsets.right;
size.height += self.edgeInsets.top + self.edgeInsets.bottom;
return size;
}
@end
After that, you can use this control easily.
//
// ExampleLink.m
//
// Created by Unocerouno on 25/4/15.
//
#import "ExampleLink.h"
#import "UILabelClickable.h"
@implementation ExampleLink
-(void)ViewDidLoad
{
UILableClickable *label = [[UILabelClickable alloc] init];
label.text = @"http://www.google.es";
[self.view addSubview: label];
}
I hope you find this code usefull, and as usual, if you will find anything to improve it, let me know.