2017-02-22 47 views
0

我创建了一个UITableView,这是我的代码吧:自定义的UITableViewCell与零的UIImageView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    // let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell") 

    let cell = SubjectCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell") 

    cell.cellUIImage.image = UIImage(named: "menu.png") 

    // cell.cellUIImage = UIImageView(UIImage(named: "menu-32.png")) 

    if indexPath.row % 2 == 0{ 
     cell.backgroundColor = UIColor.cyan 
    } 

    return cell 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 5 
} 

而且我SubjectCell类如下:

import Foundation 
import UIKit 

class SubjectCell : UITableViewCell{ 
    @IBOutlet var cellUIImage: UIImageView! 
} 

然而,当我运行此代码,它崩溃。调试,我注意到cellUIImage是零,所以它解开它时崩溃。 IBOulet链接到我的原型单元格。

linked UIImageView

解缠的是由Xcode中完成的,它不应该是零,因为它实际上是细胞UIImageView

+0

为什么不正确地从表格视图中取出单元格? – rmaddy

+0

@rmaddy特别没有理由。这是一个非常原始的代码,我通常会在之后对它进行裁剪......但是,我倒下了这不是它崩溃的原因。 –

+2

这正是它失败的原因。你的代码不会从你的xib/storyboard创建一个单元格。你只是从代码创建你的单元格。因此没有设置单元的出口。正确地创建你的细胞。正确注册单元类/笔尖,它将按预期工作。 – rmaddy

回答

-2

自iOS故事板设计发布以来,您不再需要子类UITableViewCell来创建自定义单元格。

在故事板中,选择原型单元,在属性检查器选项卡中,给定制单元一个identifier(例如:“YourCellIdentifier”)。

接下来,(仍然在故事板),选择您添加到自定义单元格的UIImageView,给它一个标签编号(例如:1000)

下面这段代码添加到cellForRowAt方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *cellIdentifier = @"YourCellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    // Here is your desired image view. 
    UIImageView *yourImageView = [cell viewWithTag:1000]; 

    return cell; 
}