如何为UITableViewHeaderFooterView设置textAlignment?

时间:2016-07-29 02:57:43

标签: ios objective-c uitableview

我制作了一个UITableViewControl。我需要为UITableViewHeaderFooterView设置textAlignment,如下所示。但它不起作用。

TableView control

UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"button.png"]]];
header.textLabel.textAlignment = NSTextAlignmentCenter;

3 个答案:

答案 0 :(得分:1)

创建视图,在此视图上添加标签,并将视图设置为表格上的标题视图:

self.tableView.headerView = view

答案 1 :(得分:0)

如果您想要一个由拉伸图像填充的标题,请尝试使用contentView代替textLabel

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HEADER_HEIGHT;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    UIImage *originImage = [UIImage imageNamed:@"yourImage"];
    CGSize size = header.frame.size;

    UIGraphicsBeginImageContext(size);
    [originImage drawInRect:CGRectMake(0,0,size.width,size.height)];
    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    header.contentView.backgroundColor = [UIColor colorWithPatternImage:resizedImage];
}

答案 2 :(得分:0)

正如@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")
}
}

使用此自定义标题视图,我们可以执行与look-n-feel相关的任何操作!