I would like to change the font type and font size of a section header in a table view controller.
My code:
func tableView(tableView: UITableView, willDi
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView,
forSection section: Int) {
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.font = UIFont(name: "Futura", size: 14)
}
There're several ways for you to archive your question by customizing the view in your storyboard, xib, tableViewCell, or you can write it by code.
After your customization completed, you can use
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let yourHeader = .....
return yourHeader
}
Updated for Swift 3
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? UITableViewHeaderFooterView
header?.textLabel?.font = UIFont(name: "Futura", size: 12) // change it according to ur requirement
header?.textLabel?.textColor = UIColor.red // change it according to ur requirement
}
func tableView(tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let hView = UIView(frame: CGRectMake(0, 0, tableView.frame.width, 44))
hView.backgroundColor = UIColor.whiteColor()
let hLabel = UILabel(frame: CGRectMake(15, 2, 30, 44))
hLabel.font = UIFont(name: "YOUR_FONT_NAME", size: 30)
hLabel.textColor = kiExtremeOrange
hLabel.text = alphabets[section]
hView.addSubview(hLabel)
return hView
}
Note:First import the font you want to use
C#
Based on Atticus' answer using willDisplayHeaderView
:
public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section)
{
var header = headerView as UITableViewHeaderFooterView;
header.TextLabel.Font = UIFont.FromName("Futura", header.TextLabel.Font.PointSize);
}
Please note that Xamarin is a cross-platform development tool for building iOS Apps using the C# language. The code above is C# and will not work in Xcode. This answer is just for developers who use Xamarin but still want to achieve what the OP also wanted.
Swift 3
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.lightGray
let headerLabel = UILabel(frame: CGRect(x: 30, y: 0, width:
tableView.bounds.size.width, height: tableView.bounds.size.height))
headerLabel.font = UIFont(name: "Verdana", size: 20)
headerLabel.textColor = UIColor.white
headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)
headerLabel.sizeToFit()
headerView.addSubview(headerLabel)
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}