【发布时间】:2012-10-01 11:16:40
【问题描述】:
我正在开发一个应用程序,它要求部分的标题应该在右侧而不是默认的左侧。
我搜索了很多极客建议实现:
- (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 坐标时,它不会影响视图的位置。而且它始终位于表格视图的中心。
我需要标题在右边。
【问题讨论】:
-
不要使用flexibleWidth,你不能强制它为全宽吗?然后视图将占用整个宽度并右对齐文本。
-
您已经选择了一个基本正确的答案,但是添加空格来获得空白是一个真正的技巧。解决问题的正确方法是创建一个空视图(或具有背景颜色的视图)并将其用作 headerView。然后将 UILabel 添加到该容器视图,并将其从右侧偏移一点。这个概念——使用一个空视图作为容器来放置其他视图是一种常见且有用的工具。
-
@DavidH 你是对的。添加空格的想法并不好。虽然它暂时对我有用。正如我在我的问题中提到的那样,视图总是在我需要它位于右侧的中心位置。设置框架不起作用。标签也是右对齐的。我知道使用 UIView 有更多的自定义选项要好得多。感谢您的评论!
-
还有一件事。按照 ilight 的建议返回 UILabel 会得到与默认值完全相同的外观。
标签: iphone objective-c ios uitableview