Заголовок раздела UITableView справа, а не по умолчанию слева
Я работаю над приложением, где требуется, чтобы заголовок секции был справа, а не по умолчанию.
Я искал, и многие вундеркинды предложили реализовать:
- (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;
}
Однако, когда я пытаюсь увеличить x-координату кадра представления заголовка, это не влияет на положение представления. И он всегда находится в центре таблицы.
Мне нужен заголовок справа.
Ответы
Ответ 1
Это сработало для меня, однако играйте с координатами кадра, чтобы выровнять в соответствии с вашими потребностями.
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *label = [[UILabel alloc] init];
[email protected]"header title";
label.backgroundColor=[UIColor clearColor];
label.textAlignment=UITextAlignmentRight;
return label;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50;
}
Ответ 2
У меня возникла проблема с изменением текста с помощью вышеупомянутого решения, это сработало для меня и мест с правильным интервалом от заднего края представления таблицы. Решение PS в 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
}
Ответ 3
firt из всех я не будет инициализировать uiview с помощью
headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)];
Поскольку координата начала координат будет 300. Для заголовка и footerviews установите начальную координату в CGPoint (0.0) и просто играйте с размером.
Попытайтесь сделать ярлык большим, чем его представление, и установите его выравнивание вправо.
UIView *headerTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
UILabel *sectionTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, headerTitleView.frame.size.width, 40)];
sectionTitleLabel.backgroundColor = [UIColor clearColor];
sectionTitleLabel.textAlignment = UITextAlignmentright;
Другая возможность - добавить UIlabel где-нибудь в правой части окна заголовка с выравниванием по центру.
Ответ 4
Я не уверен, что понимаю ситуацию, но предполагаю, что вы просто хотите, чтобы метка была выровнена правильно, а не слева.
Корректировка значения фрейма для вашего заголовка не будет работать, потому что tableView отвечает за его позиционирование, и он игнорирует любые значения, которые вы здесь задаете.
Ваш единственный вариант - работать с subviews headerView.
Пример: установка позиции headerLabel для выравнивания вправо:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static UIView *headerView;
if (headerView != nil)
return headerView;
NSString *headerText = NSLocalizedString(@"البحث الأخيرة", nil);
float headerWidth = 320.0f;
float padding = 10.0f;
headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)];
headerView.autoresizesSubviews = YES;
// create the label centered in the container, then set the appropriate autoresize mask
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, headerWidth, 44.0f)];
headerLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth;
headerLabel.textAlignment = UITextAlignmentRight;
headerLabel.text = headerText;
CGSize textSize = [headerText sizeWithFont:headerLabel.font constrainedToSize:headerLabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
headerLabel.frame = CGRectMake(headerWidth - (textSize.width + padding), headerLabel.frame.origin.y, textSize.width, headerLabel.frame.size.height);
[headerView addSubview:headerLabel];
return headerView;
}