NSTextFieldにハイパーリンクを設定する
概要
実装
HyperLinkWindowController.xib
HyperLinkWindowController.xib
- ラベル2つとButtonを貼り付けただけの簡単なUI
- 1View-1Controllerの原則により、後述の通りWindowControllerを定義していく。
HyperLinkWindowController.h
- (id)initWithMessage:(NSString *)message hyperLink:(NSString *)hyperLink;
- init関数のみ公開する
- その他は外部クラスに知らせる必要はないので、実装ファイルの
interface
に記載する
HyperLinkWindowController.m
init関数
- (id)initWithMessage:(NSString *)message hyperLink:(NSString *)hyperLink {
if (self = [super initWithWindowNibName:[self className] owner:self]) {
_message = message;
_hyperLink = hyperLink;
}
return self;
}
ハイパーリンクの設定
コード全体は以下の通り。
/**
@brief ラベルを更新する
*/
- (void)updateLabels {
// 本文の設定
[_messageLabel setStringValue:_message];
// ハイパーリンクの設定
[_hyperLinkLabel setAllowsEditingTextAttributes: YES];
[_hyperLinkLabel setSelectable: YES];
NSMutableAttributedString *attrbutedString = [[NSMutableAttributedString alloc]
initWithString:_hyperLinkLabel.stringValue
attributes:@{
NSForegroundColorAttributeName:[NSColor blueColor],
NSFontAttributeName :[NSFont systemFontOfSize:13.0f],
NSUnderlineStyleAttributeName :@(NSUnderlineStyleSingle)
}
];
[attrbutedString addAttribute:NSLinkAttributeName
value:_hyperLink
range:NSMakeRange(0, attrbutedString.length)];
[_hyperLinkLabel setAttributedStringValue:attrbutedString];
}
[_hyperLinkLabel setAllowsEditingTextAttributes: YES];
[_hyperLinkLabel setSelectable: YES];
- textFieldに
AttributedString
を設定できるようにする - ハイパーリンクの選択を許可する
NSMutableAttributedString *attrbutedString = [[NSMutableAttributedString alloc]
initWithString:_hyperLinkLabel.stringValue
attributes:@{
NSForegroundColorAttributeName:[NSColor blueColor],
NSFontAttributeName :[NSFont systemFontOfSize:13.0f],
NSUnderlineStyleAttributeName :@(NSUnderlineStyleSingle)
}
];
- textFieldに設定する
AttributesString
の変数を作成する initWithString
にはハイパーリンクの文言を設定-
attributes
にはtextFieldのUIをハイパーリンク用に設定する- 文字を
blueColor
にする - フォントのサイズを
13
にする - 下線を引く
- 文字を
[attrbutedString addAttribute:NSLinkAttributeName
value:_hyperLink
range:NSMakeRange(0, attrbutedString.length)];
[_hyperLinkLabel setAttributedStringValue:attrbutedString];
- 先程作成した
AttibutedString
の変数にNSLinkAttributeName
属性を追加する - 渡す値はハイパーリンクのURL
- rangeには今回テキスト全体をハイパーリンクにするので先頭から文字列の長さを指定
GitHub
Author And Source
この問題について(NSTextFieldにハイパーリンクを設定する), 我々は、より多くの情報をここで見つけました https://qiita.com/IKEH/items/7471b5c8a72ebe8c124f著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .