I am working on an app where it is required that the Header of section should be on right instead of the default left.
I searched and many geeks suggested to implement:
- (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;
}
However, when i try to increase the x-coordinate of Header view frame, it does not effect the position of the view. And its always in the centre of the table view.
I need the header to be on the right.
This worked for me, however play with the frame's co-ordinates to align according to your needs
-(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;
}
I had trouble changing the text with the above solution, this worked for me and places with proper spacing from the trailing edge of the table view. PS Solution in Swift
UITableViewDataSource
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With