将 cgrect 中的 tableview 单元格框架推到边距

push tableview cell frame in cgrect to margin

在下面的 swift 代码中,我希望将 tableview 单元格推到边缘,就像单元格左侧一样。在下面的照片中,您可以看到右侧 tableview 单元格的边距比左侧大很多。请使它们相等。

pic of tableview

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
    var numberOfRows = 3
  
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numberOfRows }

 
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 118
    }
    var btn = UIButton()
    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        setTableVIew()
        
      
    }
    
    func setTableVIew(){

        
        let VCframe = self.view.frame
        let height = VCframe.height * 0.8
        let widthx = VCframe.width
        
        
        tableView.frame = CGRect(x: 0, y: 0, width: widthx, height: height)

        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        tableView.backgroundColor = .blue
        
        tableView.register(customtv.self, forCellReuseIdentifier: "cell")
    }


}
class customtv: UITableViewCell {
    
   lazy var backView : UIView = {
    let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
    view.backgroundColor = .green
    print(self.frame.width)
        return view
    }()
    

    
    override func layoutSubviews() {
       backView.clipsToBounds = true

    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(animated, animated: true)
        addSubview(backView)
    }
}

更新layoutSubviews中的View frame

class customtv: UITableViewCell {
    
   lazy var backView : UIView = {
    let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
    view.backgroundColor = .green
    print(self.frame.width)
        return view
    }()
    

    
    override func layoutSubviews() {
       backView.clipsToBounds = true
       backView.frame =  CGRect(x: 0, y: 6, width: bounds.maxX  , height: 110)

    }

它们将变成等宽单元格……如果你想给边距……把它给你的表格视图而不是单元格……

tableView.frame = CGRect(x: 10, y: 0, width: widthx - 20, height: height)