How to increase the UITableView separator height?

后端 未结 17 2165
花落未央
花落未央 2020-12-08 00:19

I want more space(10px) between each cell. How can I do this?

And I have added this code

tableView.separatorStyle = UITableViewCellSepar         


        
17条回答
  •  暖寄归人
    2020-12-08 00:41

    Swift 4

    It's not possible to make the default separator higher. Instead you need to add a subview that will look as a separator to each cell (and optionally make the cell higher). You can do it for example in cellForRowAtIndexPath or in a UITableViewCell subclass.

    In case you allow to select the cell, you need to add the subview for selected state as well, otherwise the separator would disappear when the cell is selected. That's why selectedBackgroundView is also configured.

    Add this into your UITableViewController subclass:

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorStyle = .none
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
        cell.backgroundView = UIView(backgroundColor: .white)
        cell.backgroundView?.addSeparator()
    
        cell.selectedBackgroundView = UIView(backgroundColor: .blue)
        cell.selectedBackgroundView?.addSeparator()
    
        // configure the cell
    
        return cell
    }
    

    Add this extensions into the same file at the bottom:

    private extension UIView {
        convenience init(backgroundColor: UIColor) {
            self.init()
            self.backgroundColor = backgroundColor
        }
    
        func addSeparator() {
            let separatorHeight: CGFloat = 2
            let frame = CGRect(x: 0, y: bounds.height - separatorHeight, width: bounds.width, height: separatorHeight)
            let separator = UIView(frame: frame)
            separator.backgroundColor = .gray
            separator.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
    
            addSubview(separator)
        }
    }
    

提交回复
热议问题