UITableViewCell: rounded corners and shadow

前端 未结 14 1315
故里飘歌
故里飘歌 2020-12-02 05:05

I\'m changing the width of a UITableViewCell so that the cell is smaller but the user can still scroll along the edges of the tableview.

override func layout         


        
14条回答
  •  有刺的猬
    2020-12-02 05:17

    The accepted answer works but adding an extra subview to get this effect make little to no sense. Here is the solution that works.

    1st step: Add shadow and corner radius

    // do this in one of the init methods
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    
        // add shadow on cell
        backgroundColor = .clear // very important
        layer.masksToBounds = false
        layer.shadowOpacity = 0.23
        layer.shadowRadius = 4
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowColor = UIColor.blackColor().CGColor
    
        // add corner radius on `contentView`
        contentView.backgroundColor = .white
        contentView.layer.cornerRadius = 8
    }
    

    2nd step: Mask to bounds in willDisplay

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // this will turn on `masksToBounds` just before showing the cell
        cell.contentView.layer.masksToBounds = true
    }
    

    Bonus: Smooth scrolling

    // if you do not set `shadowPath` you'll notice laggy scrolling
    // add this in `willDisplay` method
    let radius = cell.contentView.layer.cornerRadius
    cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: radius).cgPath
    

提交回复
热议问题