[英]using UIImageView in accessoryView in UITableViewCell
I am trying to use a custom image for the UIAccessoryView, however I can't seem to get it to work. 我正在尝试为UIAccessoryView使用自定义图像,但是我似乎无法使其正常工作。 When the table view launches, it doesn't update with any of the images.
表格视图启动时,不会使用任何图像进行更新。 My code is the following:
我的代码如下:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
MenuItem *menuItem = [self.menuItems objectAtIndex:indexPath.row];
if (!tableViewCell)
{
tableViewCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
tableViewCell.textLabel.font = [UIFont fontWithName: CaptionDistractionBodyFontName size: 15];
imageView.contentMode = UIViewContentModeCenter;
tableViewCell.accessoryView = [[UIImageView alloc] initWithImage:nil];
}
tableViewCell.textLabel.text = menuItem.name;
UIImageView *imageView = (UIImageView*)tableViewCell.accessoryView;
imageView.image = nil;
if (menuItem.type == MenuItemTypeCheckMark)
{
if (menuItem.isCheckMarked)
{
imageView.image = [UIImage imageNamed:@"DisclosureViewX"];
}
}
else if (menuItem.type == MenuItemTypeSubmenu)
{
imageView.image = [UIImage imageNamed:@"DisclosureViewArrow"];
}
return tableViewCell;
}
I've tried a lot of different stuff, ie calling setNeedsLayout
, moving the code to a custom UITableViewCell
in layoutSubviews
and nothing seems to work. 我尝试了很多不同的东西,即调用
setNeedsLayout
,将代码移动到layoutSubviews
的自定义UITableViewCell
,似乎没有任何效果。 Aside from just creating a whole new accessory view myself, what is the correct way to go about this? 除了自己创建一个全新的附件视图之外,执行此操作的正确方法是什么?
尝试做
tableViewCell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"DisclosureViewX"]];
Since you initially setup the UIImageView
with a nil
image, the image view's frame has a zero width and height. 由于最初使用
nil
图像设置了UIImageView
,所以图像视图的框架的宽度和高度UIImageView
零。 You need to reset the frame after assigning an actual image. 分配实际图像后,需要重设相框。
imageView.image = [UIImage imageNamed:@"DisclosureViewX"];
imageView.frame = CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height);
Edit: 编辑:
Actually it would be even easier to call [imageView sizeToFit]
after setting the image instead of setting the frame
. 实际上,设置图像而不是设置
frame
之后,调用[imageView sizeToFit]
会更加容易。
I think your problem is that image view creates with zero size. 我认为您的问题是图像视图创建的尺寸为零。 Use initWithFrame: or initWithImage:, where image is not nil.
使用initWithFrame:或initWithImage :,其中image不为nil。 After created with initWithImage:, image view will have bounds set to image size.
使用initWithImage:创建后,图像视图的边界将设置为图像大小。 A cell will center the accessory view automatically.
单元格将自动使附件视图居中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.