概要
実装
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