我正在尝试使用单元格左侧的按钮创建(不是非常)自定义UITableView,并在按钮右侧添加文本。
我尝试计算将UILabel作为单元格的一部分放置在何处,但是更改框架没有任何效果(而且甚至看起来都没有计算出来-全为零)。
我的问题是:何时计算标签的帧大小? (这样更改才会有效果)。
这是正确的方法吗?
下面的代码段。
首先是从单元格init(响应于dequeueReusable调用...
是的,“buttonColor”,“onTapSel”,“buttonFrame”和“buttonColor”是“成员变量(文件静态全局变量)
- (id)initWithStyle: (UITableViewCellStyle)style
reuseIdentifier: (NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (nil == buttonColor)
{ buttonColor = kDefaultCellButtonColor; }
if (nil == onTapSel)
{ onTapSel = @selector(defaultCellButtonTapped:); }
if (self)
{
EGCellButton * cellButton = (EGCellButton *)[[EGCellButton alloc ] initWithFrame:buttonFrame ];
cellButton.backgroundColor = buttonColor;
[cellButton setTitle:buttonLabel forState:UIControlStateNormal];
[cellButton addTarget:self action:(onTapSel) forControlEvents: UIControlEventTouchUpInside];
[self setCellButton:cellButton];
float xx = buttonFrame.origin.x + buttonFrame.size.width + 5;
CGRect frame = self.textLabel.frame;
frame.origin.x += xx;
self.textLabel.frame = frame;
[self addSubview:cellButton];
}
return self;
}
现在从cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EGButtonTableCellID";
EGButtonTableCell * cell = (EGButtonTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.cellButton.indexPath = indexPath;
// Configure the cell...
cell.textLabel.text = @"abcdefghijklmnopqrstuvwxyz";
float xx = cell.cellButton.frame.origin.x + cell.cellButton.frame.size.width + 5;
CGRect frame = cell.textLabel.frame;
frame.origin.x += xx;
cell.textLabel.frame = frame;
return cell;
}
结果是该按钮出现在单元格的左侧(按预期方式),但是我在标签中看到的第一个字母是'g',因此前6个字符隐藏在按钮后面(无预期)。
当我将值转储到框架中时,两种方法中除origin.x之外的所有值都为零。
这应该工作,是吗?没有?为什么不?等等
非常感谢大家!
:bp:
最佳答案
在自定义UITableViewCell的layoutSubviews
方法中为UILabel和UIButton设置框架
请参阅有关此主题的Apple文档:
子类可以根据需要重写此方法以执行更精确的操作
其子视图的布局。仅当
子视图的自动调整大小和基于约束的行为不会
提供您想要的行为。您可以使用实现来设置
直接子视图的框架矩形。