Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

ios - Swift - how to make custom header for UITableView?

I need to add custom header to my table

I try this

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

    let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
    let label = UILabel(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
    label.text = "TEST TEXT"
    label.textColor = UIColor.whiteColor()

    self.view.addSubview(view)

    return view
}

but this doesn't work, I see nothing on table

What am I doing wrong ? Or maybe there is another ways ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best working Solution of adding Custom header view in UITableView for section in swift 4 is --

#1 first Use method ViewForHeaderInSection as below -

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
        
        let label = UILabel()
        label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
        label.text = "Notification Times"
        label.font = .systemFont(ofSize: 16)
        label.textColor = .yellow
        
        headerView.addSubview(label)
        
        return headerView
    }

#2 Also Don't forget to set Height of the header using heightForHeaderInSection UITableView method -

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

and you're all set ?? ?? ??Check it here in image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...