UIPickerViewの文字サイズを変更したい
UIPickerVIewでラベルに長い文字列を載せると切れてしまうので,サイズを小さく変更したい.
例えば,_datasがこんな感じのときについて考える.
NSArray *_datas = @[@"普通の文字列", @"けっこう長ーーーい文字列", @"かなり長ーーーーーーーーーい文字列"];
普通は,こんな感じのデリゲートメソッドを使う.
-(NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ return _datas[row]; }
すると,こんな表示になる.
「かなり長ーーーーーーーーーい文字列」が切れているのが分かる.
というわけで,サイズを変更できるようにするために,使うデリゲートメソッドを変える.
こんな感じ.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *label = (id)view; if (!label) { label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)]; } label.text = _datas[row]; label.font = [UIFont boldSystemFontOfSize:16]; return label; }
pickerView:titleForRow:forComponent:メソッドの代わりに,pickerView:viewForRow:forComponent:reusingView:メソッドを使う.*1
つまり,各行のviewをラベルとして再定義してるみたいな.
ラベルのフォントを変更すれば,サイズだけでなく字体なども変えられる.
で,実行した結果がこちら.
一応,文字サイズは小さくなり,「かなり長ーーーーーーーーーい文字列」も収まっている.
しかし,分かりにくいがラベルの背景がデフォルトの白になっているため,ピッカーの丸みを表現する影が消え,おかしくなっている.
というわけで,ラベルの背景を透明する.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *label = (id)view; if (!label) { label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)]; } label.text = _datas[row]; label.font = [UIFont boldSystemFontOfSize:16]; label.backgroundColor = [UIColor clearColor]; // 追加 return label; }
実行するとこんな感じ.
いい感じになった.
でも,文字が左に寄ってしまっている.
先頭に空白でも入れておこう…
*1:pickerView:titleForRow:forComponent:メソッドが必須メソッドだと思ってたのは秘密