我有一个函数可以查找应添加的星星数量并将其添加到堆栈 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
}
最佳答案
您需要为每个 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
关于ios - 如何通过 stackview 将图像添加到 tableview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178937/