UITableView header with different height for multiple sections iOS swift 3



When we want to display multiple sections in table view with different height of headers.
Code:    
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        switch section {
        case 0:
            return (array1.count > 0) ? 22.00
        case 1:
            return (array2.count > 0) ? 22.00
        case 2:
            return (array3.count > 0) ? 22.00
        case 3:
            return (array4.count > 0) ? 22.00
        case 4:
            return (array5.count > 0) ? 22.00

        default:
            return 22.0
        }
    }


The above tableView had 5 sections with dynamic rows.When the dynamic value is set to be zero then we will hide the header using return the header height to 0.Otherwise, we can return the normal height value.The header view will be created using the below code.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let titleView:UIView = UIView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20))
        let titleLbl:UILabel = UILabel(frame:CGRect(x: 7, y: 0, width: self.view.frame.size.width, height: 20))
        titleLbl.font = UIFont.boldSystemFont(ofSize: 17)
        titleLbl.textColor = UIColor(red: 251/255, green: 38/255, blue: 77/255, alpha: 1.0)
        switch section {
        case 0:
            titleLbl.text = "title 1"
         case 1:
            titleLbl.text = "title 2"
        case 2:
            titleLbl.text = "title 3"
        case 3:
            titleLbl.text = "title 4"
        case 4:
            titleLbl.text = "title 5"

        default:
            titleLbl.text = "title"
        }
        titleView.addSubview(titleLbl)
        return titleView
    }

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift