在Swift中连接UITableViewCell标签

tik*_*ika 2 uitableview ios

我有一个TableView Cell,里面有一个ImageViewLabel.但是当我使用以下方法连接它们时:

 @IBOutlet weak var menuListLabel: UILabel!
 @IBOutlet weak var menuListImage: UIImageView!
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

非法配置:

从ViewController到UIImageView的menuListImage出口无效.插座无法连接到重复内容.

Mik*_*rne 5

您需要创建一个继承自UITableViewCell的自定义类,并在那里配置插座.

class MyCustomTableViewCell: UITableViewCell {
   @IBOutlet weak var menuListLabel: UILabel!
   @IBOutlet weak var menuListImage: UIImageView!
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要在故事板中配置单元格.选择你的手机.打开标识检查器并将自定义类设置为"MyCustomTableViewCell".

然后,在单元格仍处于选中状态的情况下,转到"属性"检查器,并将"重用标识符"设置为"MyCustomTableViewCell".(这个标识符可以是你想要的,你只需要在调用'dequeueReusableCellWithIdentifier'时使用这个确切的值.我喜欢使用我的单元格的类名作为标识符,因此很容易记住.)

在表视图控制器中,使用自定义单元格实现构建表的必要方法.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1   // however many sections you need
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 1   // however many rows you need
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // get an instance of your cell
    let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomTableViewCell", forIndexPath: indexPath) as MyCustomTableViewCell

    // populate the data in your cell as desired
    cell.menuListLabel.text = "some text"
    cell.menuListImage.image = UIImage(named: "some image")

    return cell
}
Run Code Online (Sandbox Code Playgroud)