【问题标题】:How to add images to a tableview cell through stackview如何通过stackview将图像添加到tableview单元格
【发布时间】:2017-05-25 11:02:19
【问题描述】:

我有一个函数可以找到应该添加到堆栈视图中的星数。 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
}

【问题讨论】:

    标签: ios swift uitableview core-data


    【解决方案1】:

    您需要为每个 imageViewstackView 本身添加一个宽度约束。

    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
    

    【讨论】:

    • stackview 处于水平状态,我想我已经将 imageView 帧设置为 20 到 20。添加约束后它仍然无法正常工作
    • 你还需要添加高度约束,检查编辑
    • 添加具有相同 2 项的约束并不意味着,您需要添加具有常量的约束,如上所示。让我知道这是否适合你。
    • 这是别的东西,哈哈,我意识到我的“入口”变量有一个问题,将评级存储为 0。感谢 Joze 的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 2014-07-11
    • 2011-08-17
    相关资源
    最近更新 更多