簡體   English   中英

帶有UIImageView的快速自定義UITableViewCell。 需要將單元格調整為圖像高度

[英]Swift, custom UITableViewCell with UIImageView. Need to resize cell to image height

我正在嘗試制作應用程序,它將在表格視圖中顯示圖像。 我有帶有圖像視圖的自定義單元格。 它僅必須從url下載圖像數據:

@IBOutlet weak var tweetImage: UIImageView!
var imageData : MediaItem? { didSet { updateUI() }}

func updateUI(){
    tweetImage.image = nil
    if let url = imageData?.url {
        if let data = NSData(contentsOfURL: url) {
            tweetImage.image = UIImage(data: data)
        }
    }
}

下載后,我需要更改單元格的高度。 它必須等於圖像的高度。 我在viewController中設置了自動尺寸:

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.estimatedRowHeight = tableView.rowHeight
        tableView.rowHeight = UITableViewAutomaticDimension
    }

我對圖像設置了“寬高比”,但結果卻很奇怪。 圖像超出了單元的邊界。 也許我需要設置一些限制...我不知道。

結果:

結果

但我需要這個:

不錯的結果

如果要異步加載圖像:

加載並設置新的UIImage ,可以通過UITableView函數重新加載特定的單元格:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

在您的UIViewController中:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedRowHeight = tableView.rowHeight
    tableView.rowHeight = UITableViewAutomaticDimension
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "imageDidLoadNotification:", name:"CellDidLoadImageDidLoadNotification", object: nil)
}

func imageDidLoadNotification(notification: NSNotification) {
    if  let cell = notification.object as? UITableViewCell
        let indexPath = tableView.indexPathForCell(cell) {
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    }
}

在你的UITableViewCell中

func updateUI(){
    tweetImage.image = nil
    if let url = imageData?.url {
        if let data = NSData(contentsOfURL: url) {
            tweetImage.image = UIImage(data: data)
            NSNotificationCenter.defaultCenter().postNotificationName("CellDidLoadImageDidLoadNotification", object: self)
        }
    }
}

如果要將動態表與UITableViewAutomaticDimension一起使用,則需要正確設置約束( image )。 (對於正確的寬度和高度,建議您使用寬高比)

對於靜態表視圖,您應該實現optional func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat ,並手動計算單元格大小。

當然,您需要為單元格中的圖像設置約束

屏幕截圖

也許此屏幕截圖會為您提供幫助

暫無
暫無

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

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