将图像添加到表格单元格时,默认情况下会向左移动:
cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
如何更改它,UITableViewCell中的每个图像将自动向右移动,textLabel将在图像左侧10px。
非常感谢!
答案 0 :(得分:10)
另一种方法是创建自定义单元格并覆盖layoutSubviews
方法。
@interface CustomCell : UITableViewCell
@end
@implementation CustomCell
- (void)layoutSubviews
{
[super layoutSubviews];
// grab bound for contentView
CGRect contentViewBound = self.contentView.bounds;
// grab the frame for the imageView
CGRect imageViewFrame = self.imageView.frame;
// change x position
imageViewFrame.origin.x = contentViewBound.size.width - imageViewFrame.size.width;
// assign the new frame
self.imageView.frame = imageViewFrame;
}
@end
请注意,cellForRowAtIndexPath
您需要创建并重新使用CustomCell
而不是UITableViewCell
。
希望它有所帮助。
修改强>
#import "CustomCell.h"
// other code here...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
答案 1 :(得分:5)
在此处找到解决方案代码。
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"foo.png"]];
cell.accessoryView = imageView;
供您参考。
答案 2 :(得分:1)
试试这个:
cell.imageView.frame = CGRectMake(cell.frame.size.width - cell.imageView.frame.size.width, cell.imageView.frame.origin.y, cell.imageView.frame.size.width, cell.imageView.frame.size.height);
[cell.yourTexLabel sizeToFit];
cell.yourTexLabel.frame = CGRectMake(cell.imageView.origin.x - cell.yourTexLabel.frame.size.width - 10, cell.yourTexLabel.frame.origin.y, cell.yourTexLabel.frame.size.width, cell.yourTexLabel.frame.size.height);
答案 3 :(得分:1)
在@TomSwift https://stackoverflow.com/a/31616694/1884707
找到了更好的答案cell.contentView.transform = CGAffineTransformMakeScale(-1,1);
cell.imageView.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.textAlignment = NSTextAlignmentRight;
通过在contentView上应用变换,您可以将imageView放在右侧。
答案 4 :(得分:1)
cell.accessoryView = UIImageView(图片:UIImage(名称:" imageNmae")!)
答案 5 :(得分:0)
一种解决方案是使用自定义UITableViewCell
。步骤是:
UITableViewCell
的子类,例如LabeledImageTableViewCell
。为UILabel
和UIImageView
声明 ivars 和属性。UITableView
的内容设置为动态原型。将UIImageView
和UILabel
拖到表格视图单元格并定位它们。将单元格的类设置为LabeledImageTableViewCell
。将单元格的出口连接到UILabel
& UIImageView
的{{1}}个对象。在LabeledImageTableViewCell
的代理中(通常为UITableView
,有时为UITableViewController
)实施数据源方法,例如:
UIViewController
另外,请查看WWDC 2011中的Apple视频, UITableView更改,提示&技巧和介绍Interface Builder故事板(需要登录:https://developer.apple.com/videos/wwdc/2011/。)