Home > other >  Swift tableview 'method heightForHeaderInSection' makes section text raise
Swift tableview 'method heightForHeaderInSection' makes section text raise

Time:01-22

When heightForHeaderInSection and/or heightForFooterInSection is called, the section text raises above it's first row. I attached a screenshot to show the issue. How can I increase the section spacing without the section header being affected?

@IBOutlet weak var tableView: UITableView!

let fruits = 
["apple","pear","orange","caramel","peach","fruit","fruits"]
let numbers = ["1", "2"]

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
    if section == 0 {
        return fruits.count
    } else {
        return numbers.count
    }
}


func tableView(_ tableView: UITableView, titleForHeaderInSection 
section: Int) -> String? {
    if section == 0 {
        return "Animals"
    } else {
        return "Numbers"
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: 
"cell1", for: indexPath)
    
    if indexPath.section == 0 {
        cell.textLabel?.text = fruits[indexPath.row]
    } else {
        cell.textLabel?.text = numbers[indexPath.row]
    }
    return cell
    
}

These are the 2 methods in question:

func tableView(_ tableView: UITableView, heightForHeaderInSection 
section: Int) -> CGFloat {
    return 100
}


func tableView(_ tableView: UITableView, heightForFooterInSection 
section: Int) -> CGFloat {
    return 100
}

Red arrows indicate the unwanted space.

CodePudding user response:

You are setting the height of the header to 100. See here:

func tableView(_ tableView: UITableView, heightForHeaderInSection 
section: Int) -> CGFloat {
    return 100 // Instead try returning 30
}


func tableView(_ tableView: UITableView, heightForFooterInSection 
section: Int) -> CGFloat {
    return 100 // If you are not using a footer - return .zero
}

CodePudding user response:

I got the answer from another post.

Just add:

tableView.sectionHeaderTopPadding = 100 // or whatever number you want.

  •  Tags:  
  • Related