简体   繁体   中英

Connecting a UITableViewCell Label in Swift

I have a TableView Cell and inside that I have an ImageView and Label . But when I connect to them using:

 @IBOutlet weak var menuListLabel: UILabel!
 @IBOutlet weak var menuListImage: UIImageView!

在此处输入图片说明

Illegal Configuration:

The menuListImage outlet from the ViewController to the UIImageView is invalid. Outlets cannot be connected to repeating content.

You need to create a custom class that inherits from UITableViewCell, and configure the outlets there.

class MyCustomTableViewCell: UITableViewCell {
   @IBOutlet weak var menuListLabel: UILabel!
   @IBOutlet weak var menuListImage: UIImageView!
}

Next, you need to configure the cell in your storyboard. Select your cell. Open the Identity inspector and set the Custom Class to "MyCustomTableViewCell".

Then, with the cell still selected, go to the Attributes inspector, and set the Reuse Identifier to "MyCustomTableViewCell". (This identifier can be whatever you want, you just need to use this exact value when calling 'dequeueReusableCellWithIdentifier'. I like to use my cell's class name as the identifier so it's easy to remember.)

In your table view controller, implement the necessary methods to build your table using your custom cell.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM