ios - 如何通过 stackview 将图像添加到 tableview 单元格

标签 ios swift uitableview core-data

我有一个函数可以查找应添加的星星数量并将其添加到堆栈 View 中。堆栈 View 位于表格单元格内,因此显示从 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
}

最佳答案

您需要为每个 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

关于ios - 如何通过 stackview 将图像添加到 tableview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178937/

相关文章:

ios - Google Play 游戏服务 iOS 在登录时崩溃

swift - 如何在 ARKit 中使用环境贴图?

json - AlamoFire 4.0 + SwiftyJSON 展开深度嵌套的 JSON

ios - iOS 6/7 中的 "no index path for table cell being reused"消息是什么意思?

iPhone:如何在drawRect中换行文本?

iphone - 如何正确处理GKSession的中断?

ios - 如何在 xcode 中相互使用两个类的对象?

ios - 知道两个CGRect的交点

swift - Spritekit SKShapeNode 随机缩放,Swift

UITableView 内容未在状态栏下传递