LoginSignup
31
27

More than 5 years have passed since last update.

【Swift, Objective-C】文字列からURLを検出し、リンク表示するには?

Posted at

TTTAttributedLabelを使うと簡単だ!
TTTAttributedLabelはGitHubやCocoaPodから入手できます。

予め、プロジェクトにTTTAttributedLabelを導入しておく。
TTTAttributedLabelのインスタンスを作成します。
肝は

linkLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;

でしょう。
このプロパティをセットした後にテキストをセットすると、
URLを探し、リンク表示してくれます。

Screen Shot 2014-10-01 at 22.25.21.png

リンクを押すとSafariに移動させる。
Screen Shot 2014-10-01 at 22.25.30.png

#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起動

Swift入門 勉強記録 その2 変数、定数、文字列

Swift入門 勉強記録 その3 セミコロン

Swift入門 勉強記録 その4 数値、真偽値

Swift入門 勉強記録 その5 Tuple(組)とは

Swift入門 勉強記録 その6 数値を文字列とするには

Swift入門 勉強記録 その7 繰り返し

Swift入門 勉強記録 その8 条件分岐

Swift入門 勉強記録 その9 Optional型

Swift入門 勉強記録 その10 Collection

31
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
27