uitableviewcell 样式如何设置
1、数据源方法。数据源方法的代码,分别提供了Objective-C和Swift的两种语言代码。下面还会具体解释代码。(1)Swift 代码// Swift// ViewController.swiftfunc tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 4}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cell: UITableViewCell switch(indexPath.row) { case 1: cell = UITableViewCell(style: .Value1, reuseIdentifier: "Value1") case 2: cell = UITableViewCell(style: .Value2, reuseIdentifier: "Value2") case 3: cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "Subtitle") default: cell = UITableViewCell(style: .Default, reuseIdentifier: "Default") } cell.textLabel?.text = "Hello" cell.detailTextLabel?.text = "World" return cell}(2)Objective-C代码// Objective-C// ViewController.m- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section{ return 4;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = nil; switch ([indexPath row]) { case 1: cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Value1"]; break; case 2: cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"Value2"]; break; case 3: cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Subtitle"]; break; default: cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Default"]; break; } [[cell textLabel] setText:@"Hello"]; [[cell detailTextLabel] setText:@"World"]; return cell;}

2、cellForRowAtIndexPath说明。cellForRowAtIndexPath是UITableViewDataSource中定义的2个必需方法之一。它提出的问题是“我应该在这个索引路径上显示哪个单元格?”我们通过创建一个单元格实例并返回它,来回答这个问题。表视图将采取我们返回的单元格,并在适当的位置将其显示。
3、UITableViewCell参数。UITableViewCell接受两个参数,一个样式和一个重用标识符,现在我们将专注于style参数。该参数定义为UITableViewCellStyle,它具有4个值:default,Value1,Value2和Subtitle。所以苹果给了我们4个不同的外观,我们甚至不需要做一个定制的子类。让我们来看看这些风格是什么样的。
4、总行数和indexPath.row。第一件事,我们设置行数为4,这样我们可以看到所有四个单元格样式。接下来,我们使用indexPath参数,来决定在每一行显示哪种单元格。行索引是从0开始,所以我们看到的第一行实际上会落在“默认”("default" case)下,因为这里我没有特别调用第0行。
5、cell中的文本。我们把“Hello”文本放在单元格的textLabel属性,把“World” 文本放在单元格的detailTextLabel属性。将文本分割到这两个属性中,让我们看看到会发生什么。运行应用程序,我们看到4行,每个填充和排列不同。请记住,制作这4个cells所涉及的唯一显着差异是样式参数,看到如下图:

8、第三行,UITableViewCellStyleValue2样式。这个样式也有两个信息,主要文本在左边,右边是辅助的。颜色,对齐方式和尺寸有差异。左侧的蓝色文字,每个字体略小于默认文字。这种样式的应用很少,我就不详细介绍了。
9、第四行,UITableViewCellStyleSubtitle样式。(1)也有两个信息,这一次是垂直排列。顶部的主要文字有较大的字体,底部的辅助字体较小。(2)音乐应用程序最常使用这种风格,在第一行中有专辑标题,艺术家在第二行,或歌曲标题和艺术家。要查看示例,请转到设置>蜂窝移动网络,然后向下滚动到“使用无线局域网络与蜂窝移...”部分。
