Swift tableview单元格自动高度,带自动高度标签

时间:2016-03-14 11:30:55

标签: swift tableviewcell uitableview

我对swift有些问题。 需要制作tableview并在每个单元格中都有包含文本的图像。

这是我到目前为止所做的:

enter image description here enter image description here 第一个问题:

标签应该是自动高度,现在它会破坏字符串..

第二个问题:

图像也必须是自动高度,并且取决于标签高度。

第三个问题:

行必须是自动高度,具体取决于其内部。

TableViewController代码:

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 44.0;
    tableView.tableFooterView = UIView(frame: CGRectZero)
    tableView.registerNib(UINib(nibName: "QuoteTableViewCell", bundle: nil), forCellReuseIdentifier: "QuoteCell")

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return results.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("QuoteCell", forIndexPath: indexPath) as! QuoteTableViewCell
    cell.item = results[indexPath.row]
    return cell
}

单元格代码:

class QuoteTableViewCell: UITableViewCell {

    var item: Quote! {
        didSet {
            setupCell()
        }
    }

    @IBOutlet weak var imageField: UIView!
    @IBOutlet weak var textField: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    func setupCell() {
        self.imageField.backgroundColor = UIColor(patternImage: UIImage(named: "Bg")!)
        textField.text = item.text
    }

}

2 个答案:

答案 0 :(得分:1)

要让标签使其高度适应其内容,请在Storyboard中将其行号设置为0.

如果你想在它旁边有一个图像,为什么不把两个控件放到一个水平的StackView中呢?

要让tableView行高适应单元格内容(即标签高度),只需将它的rowHeight设置为自动:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 90.0;

答案 1 :(得分:0)

使用此metod具有该功能

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
      let lineBrakingMode =  NSLineBreakMode.ByCharWrapping
    let paragragh:NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragragh.lineBreakMode = lineBrakingMode
     let attributes:NSDictionary = [NSFontAttributeName: self.textField.font!, NSParagraphStyleAttributeName:paragragh]
    let TextSize = self.textField.text!.sizeWithAttributes(attributes)
    let TextHeight = TextSize.height + 5;

     UIView.animateKeyframesWithDuration(0.2, delay: 2.0, options: UIViewKeyframeAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.imageField.frame.height = TextHeight
        }, completion: nil)
    return TextHeight
}

}