以编程方式将图像添加到TableView单元格

Bau*_*aub 20 iphone xcode objective-c swift

我有一个UITableView从服务器获取信息并将数据发布到表视图中.每个单元格内部都是来自服务器的信息.

就本例而言,假设我们从服务器获取的信息是数字:1,2,3,4.

我想要做的是添加一个图像(以编程方式,因为涉及if语句等)到单元格的左侧,文本(1,2,等)紧挨着它.

基本上,我希望每个单元格看起来像这样:

 _____________________________________
| (IMAGE) (TEXT)                      | --CELL 0
--------------------------------------
 _____________________________________
| (IMAGE) 2                           | --CELL 1
--------------------------------------
Run Code Online (Sandbox Code Playgroud)

请原谅我的粗略插图.:)

Tom*_*myG 20

干得好:

cell.imageView.image = [UIImage imageNamed:@"image.png"];
Run Code Online (Sandbox Code Playgroud)

迅速:

cell.imageView?.image = UIImage(named: "image.png")
Run Code Online (Sandbox Code Playgroud)


Chr*_*r A 8

您可以将图像和文本添加到UITableViewController子类中的UITableViewCell,如下所示:

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

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

    [[cell imageView] setImage:anImage];
    [[cell textLabel] setText:[NSString stringWithFormat:@"%d",[indexPath row]];

     return cell;
}
Run Code Online (Sandbox Code Playgroud)

您可以利用UITableViewCell的一些"内置"属性,例如imageView,textLabel和detailTextLabel.有关更多信息,请查看"表视图编程指南".


meh*_*-uk 5

Swift 2.0版的第一个答案是:

cell.imageView?.image = UIImage(named: "image.png")
Run Code Online (Sandbox Code Playgroud)