SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

Xamarin.iOS テキストビュー

【 Xamarin 記事一覧 】

1 表示

f:id:furuya02:20140712004802p:plain:w150:left
UITextViewで複数行にわたる文字列を表示できます。
使用方法は、ラベルとほとんど同じですが、ビューのサイズに収まらない時は、自動的にスクロールして、切り捨て場行われません。

public override void ViewDidLoad() {
    base.ViewDidLoad();

    //テキストビューの生成
    var textView = new UITextView(new RectangleF(0, 0, 300, 100)) {
        Text = "ナデラCEOはインタビューで「愛される製品でこれを支えていく必要がある。これこそわれわれが奮起して取り組んでいることだ」と語った。",//表示文字列
        TextAlignment = UITextAlignment.Center,//センタリング
        TextColor = UIColor.FromRGB(50,50,100),//フォントの色
        Font = UIFont.FromName("Arial", 20f), //フォントの種類とサイズ
        Center = new PointF(View.Bounds.Width / 2, View.Bounds.Height / 2) //親ビューの中央へ配置
    };
    Add(textView);//ビューへの追加
}

2 編集

f:id:furuya02:20140712013205p:plain:w150:left
編集の可否は、プロパティEditableで指定しますが、Windowsのように見た目が変わることは有りません。


また、編集時のキーボードは、プロパティKeyboardTypeに下記の種類が指定可能です。(出現後にユーザが変更可能)
  • UIKeyboardType.Default //ローカライズ
  • UIKeyboardType.ASCIICapable //英字
  • UIKeyboardType.PhonePad //電話キー
  • UIKeyboardType.EmailAddress //メールアドレス
  • UIKeyboardType.Url //URL
  • UIKeyboardType.NumbersAndPunctuation //数字
  • UIKeyboardType.NumberPad //数字入力フル
  • UIKeyboardType.NamePhonePad //名前入力サポートの電話キー
  • UIKeyboardType.Twitter //@や#が入力しやすい
  • UIKeyboardType.WebSearch //スペースや.が入力しやすい
  • UIKeyboardType.DecimalPad //小数点ありの数値

編集開始と終了のイベントは、Started及びEndedで処理できます。

textView.Started += (s, a) => {
    (new UIAlertView("", "編集開始", null,null,"OK")).Show();
};

textView.Ended += (s, a) => {
    (new UIAlertView("", "編集終了", null, null, "OK")).Show();
};


3 アトリビュート

f:id:furuya02:20140712021718p:plain:w300:left

TextStorageのAddAttribute()で、テキストの書式を設定できます。これにより、テキストビューはリッチテキストのように扱うことが可能です。

textView.TextStorage.BeginEditing();
            
//3文字目から3文字をフォント白、背景赤
textView.TextStorage.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.White, new NSRange(3, 3));
textView.TextStorage.AddAttribute(UIStringAttributeKey.BackgroundColor, UIColor.Red, new NSRange(3, 3));
//7文字目から6文字を背景緑
textView.TextStorage.AddAttribute(UIStringAttributeKey.BackgroundColor, UIColor.Green, new NSRange(7, 6));
//15文字目から43文字にアンダーライン
textView.TextStorage.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(15, 44));

textView.TextStorage.EndEditing();

【 Xamarin 記事一覧 】