LoginSignup
1
0

More than 5 years have passed since last update.

NativeScriptからNSDictionaryをスマートに扱う

Posted at

NativeScriptからNSDictionaryを使う方法を見ていきましょう。

方法1. NSMutableDictionaryを使う

NSMutableDictionaryのオブジェクトを生成して、setObjectForKeyメソッドで一つずつ値を追加していきます。

        let attr = NSMutableDictionary.alloc<string, any>().init();

        attr.setObjectForKey(UIColor.whiteColor, NSForegroundColorAttributeName);
        attr.setObjectForKey(UIColor.blackColor, NSStrokeColorAttributeName);
        attr.setObjectForKey(-1.0, NSStrokeWidthAttributeName);

        let attrStr = NSAttributedString.alloc().initWithStringAttributes("白抜きテキスト", attr);

方法2. オブジェクトリテラルを使う

NativeScriptでは、JavaScriptのオブジェクトをNSDictionaryに変換してくれるMarshalという機能があります。(ただ、この機能について公式のどこにも明確に書かれていないようなのですが...) この機能を使うと、オブジェクトリテラルの形でNSDictionaryを定義できます。

        let txt = NSMutableAttributedString.alloc().initWithStringAttributes("白抜きテキスト", <any>{
            [NSForegroundColorAttributeName]: UIColor.whiteColor,
            [NSStrokeColorAttributeName]: UIColor.blackColor,
            [NSStrokeWidthAttributeName]: -1.0
        });

コチラのほうが、コンパクトで直感的ですね。

参考

NativeScriptのMarshalについて
https://docs.nativescript.org/runtimes/ios/marshalling/marshalling-overview

JavaScript Object to NSDictionaryについて
https://github.com/NativeScript/ios-runtime/issues/54
3つめの投稿で、開発者からJS Object -> NSDictionaryについて簡単に説明されています。

1
0
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
1
0