【发布时间】:2023-12-12 22:00:01
【问题描述】:
我试图实现圆角 tableview 单元格效果,所以我试图在我的自定义单元格类中弄乱 layoutSubviews:
override func layoutSubviews() {
// Set the width of the cell
self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width - 40, self.bounds.size.height)
super.layoutSubviews()
}
听说不建议改变单元格本身的宽度,给单元格添加一个UIView(代码中称为mainView)并添加约束+圆角半径就可以了。
我的自定义单元格现在是:
class customTableViewCell: UITableViewCell {
@IBOutlet weak var mainView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
mainView.layer.borderWidth = 2
mainView.layer.cornerRadius = 20
mainView.layer.borderColor = UIColor.black.cgColor
mainView.layer.masksToBounds = true
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
这里是包含 mainTableView 的 ViewController 的相关组件:
override func viewDidLoad() {
super.viewDidLoad()
mainTableView.rowHeight = 100
mainTableView.backgroundColor = UIColor.clear
mainTableView.delegate = self
mainTableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.mainTableView.dequeueReusableCell(withIdentifier: "customCell") as! customTableViewCell
// note that indexPath.section is used rather than indexPath.row
cell.textLabel?.text = self.animals[indexPath.row]
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16)
cell.textLabel?.textAlignment = .center
// add border and color
cell.backgroundColor = UIColor.clear
cell.layer.borderColor = UIColor.clear.cgColor
cell.layer.borderWidth = 1
//cell.layer.cornerRadius = 8
cell.clipsToBounds = true
return cell
}
我的结果是这样的:
如您所知,整个单元格都被突出显示,而不仅仅是里面的内容。
我剩下的问题是 - 有没有办法只突出显示单元格的 contentView 内的 UIView 而不是整个单元格?或者我应该不启用选择和突出显示。
请告诉我。谢谢。
【问题讨论】:
标签: ios uitableview uikit swift4 xcode9