繁体   English   中英

如何通过StackView将图像添加到TableView单元格

[英]How to add images to a tableview cell through stackview

我有一个函数,该函数查找应添加到堆栈视图中的星星数。 stackview在表格单元格内,因此显示正确的等级,该等级是从CoreData检索的。 但是,没有显示等级。

功能 ...

  func setRating(entry: Entry, ratingView: UIStackView) -> UIStackView{

    for _ in 0..<Int(entry.rating) {

        let image = UIImage(named:"ratingFilled")
        let imageView = UIImageView(image: image!)

        imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

        NSLayoutConstraint(item: image!, attribute: .height, relatedBy: .equal, toItem: image!, attribute:.width, multiplier: 1.0, constant:0.0).isActive = true

        ratingView.addArrangedSubview(imageView)
    }

    return ratingView
}

Tableview单元格调用...

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ //creates rzeusable cell and assigns cell items

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    let entry = entries[indexPath.row]

    cell.nameLabel?.text = entry.restaurantName

    cell.ratingView = setRating(entry: entry, ratingView: cell.ratingView)

    return cell
}

你需要一个宽度约束添加为各处imageView或在stackView本身。

NSLayoutConstraint(item: image!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0).isActive = true
NSLayoutConstraint(item: image!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0).isActive = true

还要确保将stackView轴设置为水平

stackView.axis = .horizontal

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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