2011-03-18 31 views
3

根据this question(以及许多Google搜索结果),当我们处于表格视图中,并且我们将单元格设置为UITableViewCellStyleSubtitle时,我们不得不调整文本在单元格标签内部位于左侧。解决方法:将textAlignment设置为UITableViewCellStyleSubtitle的中心

但是我想行的一个(其实就是行)我表视图的对齐中心......显然,这是行不通的:

cell.textLabel.textAlignment = UITextAlignmentCenter; 

所以我一直在想什么,我应该做,而不是...我不知道如何干净地做到这一点。我能想到的最好办法是改变这个特定的单元格,以便单元格的样式为UITableViewCellStyleDefault,但我不认为单元格属性是可更改的。我能想到的另一种方法是对UITableViewCell类进行子类化,但对于一个表视图单元格来说,这看起来有点矫枉过正。你认为我应该怎么做才能让最后一排对齐中心?

编辑:对于那些谁感兴趣的答案:

static NSString *CellIdentifier = @"Cell"; 
static NSString *CellIdentifierDefault = @"CellDefault"; 

UITableViewCell *cell; // = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (indexPath.row >= [data count]) 
     cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifierDefault]; 
    else 
     cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil && indexPath.row < [data count]) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
    } 
    else if(cell == nil && indexPath.row >= [data count]) { 
     //Use default style for the last cell. 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierDefault] autorelease]; 
    } 
+0

我想你应该只是最后一个单元格'UITableViewCellStyleDefault'。它比上面提到的任何事情都容易得多。 – Robin 2011-03-18 04:49:26

+0

但是我需要字幕......如果我使用默认样式,如何显示text.detailTextLabel? – 2011-03-18 04:54:04

+0

你必须只为最后一行而不是任何其他行(如你在你的问题中提问) – Robin 2011-03-18 04:59:09

回答

2

@the_great_monkey:

您可以更改为cellIdentifier您希望这个中心对齐的单元格。

对于其他的细胞,你应该保持一个共同的cellIdentifier

然后,当你这样做

cell.textLabel.textAlignment = UITextAlignmentCenter; 
cell.detailTextLabel.textAlignment = UITextAlignmentCenter; 

然后简单的,你需要检查是否cellIdentifier是一个需要中心对齐的电池?

如果是,再申请,

cell.textLabel.textAlignment = UITextAlignmentCenter;cell.detailTextLabel.textAlignment = UITextAlignmentCenter;该小区。

希望这可以帮助你。

+0

如何检查单元格的cellIdentifier?我试过如果(cell.cellIdentifier == cellSubtitle)但它不工作... – 2011-03-18 09:34:26

+0

没关系。得到它了!谢谢! – 2011-03-18 09:42:58

+0

@the_great_monkey:不客气。对不起没有回复你的第一个评论,因为没有在线提供。但我很高兴它帮助你! :-) – 2011-03-18 09:55:57

0

可以很容易地从一个的.xib,它可以让你安排的单元格的子视图,你喜欢的任何方式负荷的小区中。不幸的是,UITableViewCell的textLabel和detailTextLabel属性不是IBOutlets,所以你不能连接你想要在IB中使用这些属性的标签。处理这种

的方法之一是这些意见网点连接在你的控制器代替,并使用它们,当你设置在-tableView细胞:的cellForRowAtIndexPath :.如果您以后不需要更改单元格的内容,那很好。在这种情况下,你可以创建一个包含一个UITableViewCell笔尖,设置文件拥有者的类型控制器匹配,并设置单元格的子视图,只要你喜欢把它们连起来文件的所有者。有关更多信息,请参阅Loading Custom TableView Cells from Nib Files

另一种方式去是创建具有文本标签和细节标签网点的UITableViewCell子类。然后像上面那样做,但使用你的子类而不是UITableViewCell。一旦你创建了这个子类,你可以在不同的.xibs中使用它,如果你在某个时候需要不同的布局。创建子类所需的工作很少,并且它变成了一个有用且可重用的工具。

0
cell.textLabel.textAlignment=UITextBorderStyleLine; 
相关问题