【问题标题】:changing font by scrolling UIPickerView通过滚动 UIPickerView 更改字体
【发布时间】:2015-06-26 09:36:18
【问题描述】:

是否可以在向下/向上滚动具有系统字体所有正确名称的 UIPickerView 时更改文本的字体?以便文本将其字体更改为当前在 pickerView 中选择的字体。

【问题讨论】:

  • 您希望UIPickerView 上的字体在用户滚动浏览字体列表时发生变化吗?还是您希望字体的每个名称都显示在字体本身中?

标签: ios xcode fonts uipickerview


【解决方案1】:

您可以获取所有系统字体并将其用作您的数据源

for(NSString *familyName in [UIFont familyNames]) {
     for(NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
     NSLog(@"%@", fontName);
   }
}

实现您的委托,您可以为每一行创建自定义视图

- (UIView *)pickerView:(UIPickerView *)pickerView
        viewForRow:(NSInteger)row
      forComponent:(NSInteger)component
       reusingView:(UIView *)view {

  UILabel *pickerLabel = (UILabel *)view;

  if (pickerLabel == nil) {
    CGRect frame = CGRectMake(0.0, 0.0, 80, 32);
    pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    [pickerLabel setTextAlignment:UITextAlignmentLeft];
    [pickerLabel setBackgroundColor:[UIColor clearColor]];
    [pickerLabel setFont:/*font from datasource*/];
  }

  [pickerLabel setText:[pickerDataArray objectAtIndex:row]];

  return pickerLabel;

}

【讨论】:

    【解决方案2】:

    您可以设置一个方法,用于 UIPickerView 在上/下滚动时更改选择,在 viewdidload 中,或 UIPickerview 出现的方法,例如

    [uorPickerView addTarget:self action:@selector(ValueChanged:) forControlEvents: UIControlEventValueChanged];
    

    您可以在 ValueChanged 方法中设置从 UIPickerview 中选择的字体,如

    -(void)ValueChanged :(UIPickerView *) sender {
          //Lets say you have UILable or UITextfield or UITextview as textView, so u can set your text like, 
          // fontArray = Array you have provided for UIPickerView datasource
          [textView setFont:[UIFont fontWithName:[fontArray objectAtIndex:[sender selectedRowInComponent:0]] size:16]]
          // make sure that fontArray has proper value of font family.
    } 
    

    希望对你有所帮助,

    HTH,享受编码!

    【讨论】:

    • 它帮助解决了我的问题,谢谢。抱歉回复晚了。
    • addTarget 不适用于 PickerView
    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 2012-07-06
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多