UITableView部分标题在右边而不是默认在左边

Abd*_*mer 12 iphone objective-c uitableview ios

我正在开发一个应用程序,其中要求部分的标题应该在右侧而不是默认的左侧.

我搜索了很多极客建议实施:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static UIView *headerView;

    if (headerView != nil)
        return headerView;

    NSString *headerText = NSLocalizedString(@"????? ???????", nil);

    // set the container width to a known value so that we can center a label in it
    // it will get resized by the tableview since we set autoresizeflags
    float headerWidth = 150.0f;
    float padding = 10.0f; // an arbitrary amount to center the label in the container

    headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)];
    headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    // create the label centered in the container, then set the appropriate autoresize mask
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, 0, headerWidth - 2.0f * padding, 44.0f)];
    headerLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    headerLabel.textAlignment = UITextAlignmentRight;
    headerLabel.text = headerText;

    [headerView addSubview:headerLabel];

    return headerView;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试增加标题视图框的x坐标时,它不会影响视图的位置.它始终位于桌面视图的中心.

我需要标题在右边.

ili*_*ght 15

这对我有用,但是可以根据您的需要使用框架的坐标进行调整

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];
    label.text=@"header title";
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment = NSTextAlignmentRight;
    return label;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用`UITextAlignmentRight`,应使用`NSTextAlignmentRight` (3认同)

小智 7

我无法使用上述解决方案更改文本,这对我和从表视图的后缘有适当间距的位置起作用.Swift中的PS解决方案

UITableViewDataSource

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 30
}
Run Code Online (Sandbox Code Playgroud)

的UITableViewDelegate

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Header Title"
}

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.textLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14.0)
    header.textLabel?.textAlignment = NSTextAlignment.Right

}
Run Code Online (Sandbox Code Playgroud)