我正在尝试以编程方式创建一个具有不同高度的tableview单元格。
// Created by AJ Norton on 7/29/15.
// Copyright (c) 2015 AJ Norton. All rights reserved.
import UIKit
class ViewController: UITableViewController {
var arr = ["image1.jpg", "image2.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "he"
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
self.tableView.registerClass(CustCellTableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustCellTableViewCell
cell.label.text = arr[indexPath.row]
cell.imageContainer.image = UIImage(named: arr[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var i = UIImage(named: arr[indexPath.row])!
return CGFloat(i.size.height + 15.0)
}
}
这是我的自定义单元格:
// Created by AJ Norton on 7/29/15.
// Copyright (c) 2015 AJ Norton. All rights reserved.
import UIKit
class CustCellTableViewCell: UITableViewCell {
lazy var imageContainer: UIImageView = {
var i = UIImageView()
i.setTranslatesAutoresizingMaskIntoConstraints(false)
return i
}()
lazy var label: UILabel = {
var l = UILabel()
l.setTranslatesAutoresizingMaskIntoConstraints(false)
l.textColor = UIColor.redColor()
return l
}()
override func layoutSubviews() {
self.addSubview(label)
self.addSubview(imageContainer)
self.backgroundColor = UIColor.greenColor()
var viewDict = ["label": label, "image": imageContainer]
var constraint1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[image]-5-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDict)
var constraint2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]-[image]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDict)
var constraint3 = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDict)
self.addConstraints(constraint1)
self.addConstraints(constraint2)
self.addConstraints(constraint3)
self.sizeToFit()
}
}
答案 0 :(得分:0)
只需删除self.sizeToFit()即可。