iDeveloper iDeveloper - 1 month ago 7
Swift Question

Unable to set textLabel in viewForHeaderInSection [UITableView]

I am getting textLabel value from API Successfully. But unable to set in viewForHeaderInSection. In my app there are different section at different index, means some time I get two section, some time one and some time three

I am try this Code -

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

let headerView = HeaderView(tableView: self.tblView, section: section)
headerView.backgroundColor = UIColor.whiteColor()
let subjectNameLabel = UILabel(frame: CGRect(x: 19, y: 4, width: 282, height: 35))

subjectNameLabel.textAlignment = NSTextAlignment.Center
subjectNameLabel.font = UIFont (name: "HelveticaNeue", size: 16)
subjectNameLabel.textColor = UIColor.whiteColor()
headerView.userInteractionEnabled = true

let dataArrayTblView = dataArrayForTableView
let subjectNameTxtValue = dataArrayTblView.valueForKey("subjectname")

subjectNameLabel.text = subjectNameTxtValue as? String
subjectNameLabel.backgroundColor = UIColor(red: 75/255.0, green: 193/255.0, blue: 210/255.0, alpha: 1.0)

headerView.addSubview(subjectNameLabel)

return headerView
}

Answer

Try My code.

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let frame: CGRect = tableView.frame
        let title: UILabel = UILabel(frame: CGRectMake(50, 3, 200, 30))
        title.text = TotalSection[section] as AnyObject! as! String!
        title.textColor = UIColor.whiteColor()
        title.font = UIFont(name: "OpenSans-Semibold",
                            size: 15.0)
        let headerView: UIView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
        headerView.addSubview(title)

        headerView.layer.backgroundColor = BUTTON_SUBMIT_LIGHT_BLACK.CGColor
        return headerView
}

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