アプリ上のリンクから、ローカルのHTMLを開くようにしたい
- HTMLファイルはアプリ内部にもたせる
- macOS アプリ
- ObjectiveC / Xcode11
- 開く処理は、通常のボタンクリックで開くかたち
- 見た目はテキストボックスっぽく変更( Interface Builder で少しいじった)
- リンクっぽい見た目はNSMutableAttributedString でNSLinkAttributeName をつかった
- (void)viewDidLoad { [super viewDidLoad]; // 見た目用にNSMutableAttributedStringのNSLinkAttributeName を使う NSMutableAttributedString *attrStr = [[NSMutableAttributedString new] initWithString:@"リンクをブラウザで開く"]; [attrStr addAttribute:NSLinkAttributeName value:@"Dummy" range:NSMakeRange(0,[attrStr length])]; [self.openLinkButton setAttributedTitle:attrStr]; } - (IBAction)pushLinkButton:(id)sender { // 実際に開く処理はボタン押下で実施 NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle pathForResource:@"Docs/index" ofType:@"html"]; NSURL *localHTMLUrl = [[NSURL alloc] initFileURLWithPath:path isDirectory:false]; [NSWorkspace.sharedWorkspace openURL:localHTMLUrl]; }
●最初はNSMutableAttributedString のみで実現したかった
やり方がわからなかった。
NSURLで file://... を設定すると、ファイルのある場所が開かれてしまった…。(ブラウザで開いてほしい)
見た目のために NSMutableAttributedString 処理は残した
●ローカルファイルを階層を維持した状態で含めたい
含めたいフォルダ/ファイルをプロジェクトに追加する際、Create groups ではなく、Create folder references を選択して追加する
参考: