我有一个分组的tableview,起初我想删除顶部和底部分隔符。我环顾四周,发现一个对我很有效的解决方案。这是通过在单元格底部添加UIView来充当分隔符。现在看起来很棒。但是我遇到的问题是设置单元格的AccessoryView时,因为由于某些原因,当选择单元格时,我的自定义分隔符会更改其宽度。这是问题的表示:
这是未选中的时候
这是在选择时:
请注意,自定义分隔符已经具有约束条件。
有什么建议吗?
编辑:
这是设置附件视图的方法:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) as? TableViewCell {
let label = UILabel()
label.text = "x"
label.sizeToFit()
label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
if(cell.accessoryView == nil){
cell.accessoryView = label
}else{
cell.accessoryView = nil
}
}
}
就这样,其他所有内容都只是一个带有行和节的简单表格视图,我还在情节提要中将分隔符设置为无。
编辑2:
答案 0 :(得分:1)
答案 1 :(得分:0)
在iOS 13+中,我不得不更改代码以在单元格而不是单元格的contentView上绘制底部边框。我是在Cell类的awakeFromNib
中完成的。
override func awakeFromNib() {
super.awakeFromNib()
addBorder(borderType: .bottom)
}
func addBorder(borderType: BorderType, width: CGFloat = 1.0, color: UIColor = .darkGray) {
// figure out frame and resizing based on border type
var autoresizingMask: UIView.AutoresizingMask
var layerFrame: CGRect
switch borderType {
case .left:
layerFrame = CGRect(x: 0, y: 0, width: width, height: self.bounds.height)
autoresizingMask = [ .flexibleHeight, .flexibleRightMargin ]
case .right:
layerFrame = CGRect(x: self.bounds.width - width, y: 0, width: width, height: self.bounds.height)
autoresizingMask = [ .flexibleHeight, .flexibleLeftMargin ]
case .top:
layerFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: width)
autoresizingMask = [ .flexibleWidth, .flexibleBottomMargin ]
case .bottom:
layerFrame = CGRect(x: 0, y: self.bounds.height - width, width: self.bounds.width, height: width)
autoresizingMask = [ .flexibleWidth, .flexibleTopMargin ]
}
// look for the existing border in subviews
var newView: UIView?
for eachSubview in self.subviews {
if eachSubview.tag == borderType.rawValue {
newView = eachSubview
break
}
}
// set properties on existing view, or create a new one
if newView == nil {
newView = UIView(frame: layerFrame)
newView?.tag = borderType.rawValue
self.addSubview(newView!)
} else {
newView?.frame = layerFrame
}
newView?.backgroundColor = color
newView?.autoresizingMask = autoresizingMask
}