中心在UITableViewCell问题中对齐文本

Mag*_*pie 64 iphone objective-c ios4

我是Objective-C和iPhone开发的新手,在尝试将文本放在表格单元格中时遇到了一个问题.我搜索了谷歌,但解决方案是针对旧的SDK错误已修复,这些对我不起作用.

一些代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = @"Please center me";
    cell.textLabel.textAlignment = UITextAlignmentCenter;
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

以上内容并非文本的中心.

我也试过了willDisplayCell方法:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.textAlignment = UITextAlignmentCenter;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了一些旧的解决方案:

UILabel* label = [[[cell contentView] subviews] objectAtIndex:0];
label.textAlignment = UITextAlignmentCenter;
return cell;
Run Code Online (Sandbox Code Playgroud)

这些都不会对文本对齐产生任何影响.我已经没有想法了,任何帮助都会受到最高的赞赏.

提前干杯.

小智 125

不知道它是否有助于解决您的具体问题,但是UITextAlignmentCenter如果您使用它会起作用initWithStyle:UITableViewCellStyleDefault

  • 这有助于我没有使用微妙的细胞我想要居中.谢谢.我猜UITextAlignmentCenter不适用于UITableViewCellStyleSubtitle单元格. (4认同)
  • `UITextAlignmentCenter`现已弃用.请参阅[此文章](http://stackoverflow.com/a/12793054/2521004)以获得更好的选择. (2认同)
  • 完善.Apple的某个人应该通过向我们提供无法解释如何解决问题的错误消息来解雇.如果不是stackoverflow和像你这样的人,我们都会搞砸. (2认同)

voi*_*ern 16

它不起作用,因为textLabel它只是对任何给定文本所需的宽度.(UITableViewCell设置为UITableViewCellStyleSubtitle样式时,将标签移动到适合的位置)

您可以覆盖layoutSubviews以确保标签始终填充单元格的整个宽度.

- (void) layoutSubviews
{
    [super layoutSubviews];
    self.textLabel.frame = CGRectMake(0, self.textLabel.frame.origin.y, self.frame.size.width, self.textLabel.frame.size.height);
    self.detailTextLabel.frame = CGRectMake(0, self.detailTextLabel.frame.origin.y, self.frame.size.width, self.detailTextLabel.frame.size.height);
}
Run Code Online (Sandbox Code Playgroud)

一定要保持高度/ y位置相同,因为只要detailTextLabel文本为空,textLabel就会垂直居中.


Tej*_*der 6

使用此代码:

cell.textLabel.textAlignment = NSTextAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)

上面的代码将起作用。不要使用UITextAlignmentCenter,它已被弃用。