正如@wg_hij所建议的那样,我们可以使用自定义UIView
作为表视图的标题视图。
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionInfo = fetchedResultsController!.sections! as [NSFetchedResultsSectionInfo]
let headerTitle = sectionInfo[section].name
let headerHeight:CGFloat = tableView.sectionHeaderHeight
let headerView = HeaderView(frame: CGRectMake(0, 0, tableView.width, headerHeight), withHeaderLable: headerTitle)
return headerView
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;//custom height
}
HeaderView
将是这样的:
class HeaderView: UIView {
var headerLbl: UILabel?
init(frame: CGRect, withHeaderLable headerText: String) {
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
makeUpHeaderLabel(headerText)
}
func makeUpHeaderLabel(lblText: String) {
if headerLbl == nil {
headerLbl = UILabel(frame: CGRectMake(0, 0, 10, 10))
headerLbl!.makeRoundedRect()
headerLbl!.bgColorName = ColorPaletteCP1
headerLbl!.fontName = BHTypoMI14
headerLbl!.textAlignment = .Center
headerLbl!.baselineAdjustment = .AlignCenters
addSubview(headerLbl!)
}
headerLbl!.text = lblText
headerLbl!.sizeToFit()
let frame = headerLbl!.frame
headerLbl!.frame = CGRectMake(0, 0, frame.size.width + 32, frame.height + 8)
headerLbl!.center = CGPointMake(width/2, height/2)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
使用这种自定义标题视图,我们可以做一下正感觉相关的东西!
它居中。标签不是标题的全部宽度。我猜你想要在屏幕中间的文字? – KevinS
它居中。但是现在,我想设置像图片一样的标题!你可以帮我吗? –