TTTAttributedLabelを使うと簡単だ!
TTTAttributedLabelはGitHubやCocoaPodから入手できます。
予め、プロジェクトにTTTAttributedLabelを導入しておく。
TTTAttributedLabelのインスタンスを作成します。
肝は
linkLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
でしょう。
このプロパティをセットした後にテキストをセットすると、
URLを探し、リンク表示してくれます。
#import "ViewController.h"
#import <TTTAttributedLabel.h>
// リンクをタップしたときのDelegate処理
@interface ViewController ()<TTTAttributedLabelDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// URLが含まれているテキストを用意
NSString *text = @"私はロケットニュース24(http://rocketnews24.com)が大好きです。\nGIGAZINE(http://gigazine.net)も好き。";
TTTAttributedLabel *linkLabel = [[TTTAttributedLabel alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
linkLabel.delegate = self;
linkLabel.numberOfLines = 0;
// セットした文字列からURLを見つけてくれるように設定
linkLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
// リンクを押しているときのフォントを指定
linkLabel.activeLinkAttributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:12.0f]
};
// 表示する文字列をセット
[linkLabel setText:text];
// 表示
linkLabel.center = self.view.center;
[self.view addSubview:linkLabel];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// リンクをタップしたときの処理
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
// Safariで開く
if ([[UIApplication sharedApplication]canOpenURL:url]){
[[UIApplication sharedApplication]openURL:url];
}
}
@end
import UIKit
class ViewController: UIViewController , TTTAttributedLabelDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// URLが含まれているテキストを用意
let text = "私はロケットニュース24(http://rocketnews24.com)が大好きです。\nGIGAZINE(http://gigazine.net)も好き。"
let linkLabel = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
linkLabel.delegate = self
linkLabel.numberOfLines = 0
// セットした文字列からURLを見つけてくれるように設定
linkLabel.enabledTextCheckingTypes = NSTextCheckingType.Link.toRaw()
// リンクを押しているときのフォントを指定
linkLabel.activeLinkAttributes = [NSFontAttributeName:UIFont.systemFontOfSize(12.0)]
// 表示する文字列をセット
linkLabel.setText(text)
// 表示
linkLabel.center = self.view.center
self.view.addSubview(linkLabel)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// リンクをタップしたときの処理
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
// Safariで開く
if UIApplication.sharedApplication().canOpenURL(url){
UIApplication.sharedApplication().openURL(url)
}
}
}
・Swiftに関する他の記事はこちら
Swift入門 勉強記録 その1 Swiftとは、Playground起動