【发布时间】:2020-11-21 03:46:08
【问题描述】:
我在代码中完成了自定义 UITableViewCell,但是我在使用带有 SfSymbol 的圆形 UIImageView 时遇到了问题。有时它运行良好,如您在屏幕截图中看到的那样,但有时它有一些奇怪的形状。如果我不设置任何 SfSymbol 形状是好的。
我认为我尝试了任何我可以尝试的方法,但仍然无法正常工作。这是我的自定义单元格代码:
import UIKit
class ListsTableViewCell: UITableViewCell {
// MARK: - Properties
let configuration = UIImage.SymbolConfiguration(pointSize: 16, weight: .medium)
var list: List? {
didSet {
guard let list = list else { return }
iconView.backgroundColor = list.color
titleLabel.text = list.name
}
}
// MARK: - Layout properties
var iconView: CircularImageView!
var titleLabel: UILabel!
// MARK: - Initialization
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
iconView = CircularImageView()
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.tintColor = .white
iconView.contentMode = .center
titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(iconView)
contentView.addSubview(titleLabel)
NSLayoutConstraint.activate([
iconView.heightAnchor.constraint(equalToConstant: 34),
iconView.widthAnchor.constraint(equalToConstant: 34),
iconView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
iconView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
iconView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
iconView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
titleLabel.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: 12),
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
titleLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是行函数的表格视图单元格:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let list = listsToDisplay![indexPath.row]
let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "list", for: indexPath) as! ListsTableViewCell
tableViewCell.iconView.image = UIImage(systemName: list.icon, withConfiguration: tableViewCell.configuration)
tableViewCell.list = list
tableViewCell.accessoryType = .disclosureIndicator
return tableViewCell
}
这是 UIImageView 的自定义子类
import UIKit
class CircularImageView: UIImageView {
override func layoutSubviews() {
self.layer.masksToBounds = true
self.clipsToBounds = true
self.layer.cornerRadius = self.frame.size.width / 2
}
}
【问题讨论】:
-
您是否收到任何有关违反约束的警告?
-
是的,我有。单元格大小有问题。它向我展示了一些奇怪的约束: UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7faa33e1d0c0.height == 54.3333
-
我认为您不需要设置高度和宽度限制。你为什么不试试没有它。
-
我试过了,还是不行。
-
@sirekpiotr - 显示它“有时它有一些奇怪的形状”时的样子
标签: ios uitableview uiimageview uikit