【问题标题】:attributed text not working on TableView Cell属性文本不适用于 TableView 单元格
【发布时间】:2013-12-05 10:11:32
【问题描述】:

尝试在 TabelViewCell 上使用不同的字体和字体大小,但它不起作用。

这是我尝试过的:

cell.textLabel.attributedText = [infoCells objectAtIndex:indexPath.row];

此代码使应用程序崩溃

然后我尝试了这个:

cell.textLabel.text = [infoCells objectAtIndex:indexPath.row];

现在一切正常,但字体和字体大小没有改变。

以下是我的应用程序中的更多代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    infoCells  = [[NSMutableArray alloc] initWithCapacity:2];


    [infoCells addObject:@"DOI"];
    [infoCells addObject:@"WIS?"];
    [infoCells addObject:@"اللَّهُمَّ إِنِّي أَسْتَخِيرُكَ بِعِلْمِكَ وَأَسْتَقْدِرُكَ بِقُدْرَتِكَ"];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


    // Configure the cell...

    cell.textLabel.attributedText = [infoCells objectAtIndex:indexPath.row];

    cell.textLabel.font = [UIFont fontWithName:@"Adobe Arabic" size:20];

    return cell;  

}

【问题讨论】:

  • 您的数组infoCells 不包含任何NSAttributedString 对象。只是普通的NSString 对象。
  • 我如何使字符串属性化?
  • 您创建 NSAttributedString 对象并提供正确的属性。
  • 创建 NSAttributedString 而不是 NSString 。

标签: ios iphone objective-c ios7 textkit


【解决方案1】:

您需要创建一个 NSMutableAttributedString 字符串,然后分配它。因此,有关更多信息,请参阅此示例。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


        // Configure the cell...

    NSMutableAttributedString *str=[[NSMutableAttributedString alloc] initWithString:[infoCells objectAtIndex:indexPath.row]];
 [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:50] range:NSMakeRange(0, str.length)];

        cell.textLabel.attributedText = str;

        //cell.textLabel.font = [UIFont fontWithName:@"Adobe Arabic" size:20];

        return cell;  

    }

【讨论】:

  • 仍然出现错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSConcreteMutableAttributedString addAttribute:value:range:: nil value'
  • 它说你的字体不再退出所以请改变你的字体。所以请看现在编辑的答案。
  • 再次出现同样的错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSConcreteMutableAttributedString addAttribute:value:range:: nil value'
  • 你确定你的字符串 [infoCells objectAtIndex:indexPath.row] 不为空吗?
  • 你没有添加任何字体
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多