簡體   English   中英

在UITableViewCell的附件視圖中使用UIImageView

[英]using UIImageView in accessoryView in UITableViewCell

我正在嘗試為UIAccessoryView使用自定義圖像,但是我似乎無法使其正常工作。 表格視圖啟動時,不會使用任何圖像進行更新。 我的代碼如下:

- (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;
}

我嘗試了很多不同的東西,即調用setNeedsLayout ,將代碼移動到layoutSubviews的自定義UITableViewCell ,似乎沒有任何效果。 除了自己創建一個全新的附件視圖之外,執行此操作的正確方法是什么?

嘗試做

tableViewCell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"DisclosureViewX"]];

由於最初使用nil圖像設置了UIImageView ,所以圖像視圖的框架的寬度和高度UIImageView零。 分配實際圖像后,需要重設相框。

imageView.image = [UIImage imageNamed:@"DisclosureViewX"];
imageView.frame = CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height);

編輯:

實際上,設置圖像而不是設置frame之后,調用[imageView sizeToFit]會更加容易。

我認為您的問題是圖像視圖創建的尺寸為零。 使用initWithFrame:或initWithImage :,其中image不為nil。 使用initWithImage:創建后,圖像視圖的邊界將設置為圖像大小。 單元格將自動使附件視圖居中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM