Stuck understanding how to create a table with multiple columns in iOS Swift

前端 未结 3 1283
借酒劲吻你
借酒劲吻你 2021-02-02 00:47

I\'ve spent the better half of the day so far researching and trying to understand how to make a table with multiple columns. Embarrassingly, I am still quite new to Swift and p

3条回答
  •  后悔当初
    2021-02-02 01:32

    In IB I set up a tableview and added a stackview in the content view (can be done programmatically). The labels are setup programmatically since it allows me to set the width of each column as a fraction of the cell width. Also, I acknowledge that some of the calculations inside the table view cellForRow method should be moved out.

     import UIKit
    
    class tableViewController: UITableViewController {
    var firstTime = true
    var width = CGFloat(0.0)
    var height = CGFloat(0.0)
    var cellRect = CGRectMake(0.0,0.0,0.0,0.0)
    
    let colors:[UIColor] = [
        UIColor.greenColor(),
        UIColor.yellowColor(),
        UIColor.lightGrayColor(),
        UIColor.blueColor(),
        UIColor.cyanColor()
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    // workaround to get the cell width 
        cellRect = CGRectMake(0, 0, self.tableView.frame.size.width ,44);
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    
    }
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 3
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    var cellWidth = CGFloat(0.0)
    var cellHeight = CGFloat(0.0)
    let widths = [0.2,0.3,0.3,0.2]
    let labels = ["0","1","2","3"]
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
            let v = cell.contentView.subviews[0] // points to stack view
            // Note: using w = v.frame.width picks up the width assigned by xCode.
            cellWidth = cellRect.width-20.0 // work around to get a right width
            cellHeight = cellRect.height
    
            var x:CGFloat = 0.0
            for i in 0 ..< labels.count {
                let wl = cellWidth * CGFloat(widths[i])
                let lFrame = CGRect(origin:CGPoint(x: x,y: 0),size: CGSize(width:wl,height: cellHeight))
                let label = UILabel(frame: lFrame)
                label.textAlignment = .Center
                label.text = labels[i]
                v.addSubview(label)
                x = x + wl
                print("i = ",i,v.subviews[i])
                v.subviews[i].backgroundColor = colors[i]
            }
    
    
        return cell
    }
    
    
    }
    

提交回复
热议问题