简体   繁体   中英

TableViewController with custom cells in swift

I'm having an issue with custom TableViewCell in Swift. I'm trying to display a custome TableViewCell in a TableView but that doesn't work well. I got a grey square on the screen... I found some answers on the Internet that recommend to disable Auto-Layout. I did it but now, my cell is displayed but there is a mess with the height of the cells. As you can see, my cell that is supposed to have red background is displayed on the height of 3 cells while the background is on only 1 cell. The height of the cell and the Row Height are both set to 150px.

           With Auto-Layout:                   Without Auto-Layout:

在此处输入图片说明在此处输入图片说明

Here is the Cell code:

class CharacterDescription : UITableViewCell {
    @IBOutlet var imageProfile: UIImageView!
    @IBOutlet var name: UILabel!
    @IBOutlet var hp: UILabel!
    @IBOutlet var damages: UILabel!
    @IBOutlet var range: UILabel!
    @IBOutlet var mp: UILabel!
    @IBOutlet var critChances: UILabel!
    @IBOutlet var critModifier: UILabel!

    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
    }
}

And the TableViewController code:

class CharacterDescriptionsViewController : UITableViewController, UITableViewDataSource, UITableViewDelegate {
    var userProfile: UserProfile!

    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }

    override init() {
        super.init()
    }

    override func viewDidLoad() {
        var nibName = UINib(nibName: "CharacterDescription", bundle:nil)

        self.tableView.registerNib(nibName, forCellReuseIdentifier: "CharacterDescription")
    }

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return userProfile.characters!.count
    }


    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        var cell = self.tableView.dequeueReusableCellWithIdentifier("CharacterDescription", forIndexPath: indexPath) as CharacterDescription

        //!TODO: Init of cell
        return cell
    }
}

您必须重写TableView.heightForRowAtIndexPath才能返回自定义单元格的高度。

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