0

Good day! I have 2 problems and I hope you will help me.

1) I have news feed in my application, that contains images. I am using Autolayout for dynamic cells: https://i.stack.imgur.com/DGWua.png

and I want the image to keep its ratio and to completely fill the width of the cell (with margins = 12). I set constrains, cell is autoresizable, but image didn't save its ratio:

https://i.stack.imgur.com/OSMfz.png .

What I am doing wrong?

2) The second problem, i load images asynchronously, here is my code:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: EventCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as EventCell
    var rowData: NSDictionary = tableData[indexPath.row] as NSDictionary
    cell.titleButton.setTitle(rowData["title"] as? String, forState: UIControlState.Normal)
    cell.titleButton.addTarget(self, action: "openWebSite:", forControlEvents: UIControlEvents.TouchUpInside)
    cell.titleButton.tag = indexPath.row
    cell.descriprionLabel.text = rowData["description"] as? String
    var urlString = rowData["image"] as String
    var image = imageCache[urlString]
    if( image == nil ) {
        var imgURL = NSURL(string: urlString)

        // Download an NSData representation of the image at the URL
        var request: NSURLRequest = NSURLRequest(URL: imgURL!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            if error == nil {
                image = UIImage(data: data) // data -> image
                // Store the image in to our cache
                self.imageCache[urlString] = image // save in our dictionary
                if let cellToUpdate : EventCell = tableView.cellForRowAtIndexPath(indexPath) as? EventCell {
                    self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
                }
            }
            else {
                println("Error: \(error.localizedDescription)")
            }
        })
    } else {
        dispatch_async(dispatch_get_main_queue(), {
            if let cellToUpdate : EventCell = tableView.cellForRowAtIndexPath(indexPath) as? EventCell  {
                cellToUpdate.img.image = image
            }
        })
    }
    cell.selectionStyle = UITableViewCellSelectionStyle.None;
    cell.contentView.setNeedsLayout(); // autolayout bug solution
    cell.contentView.layoutIfNeeded(); // autolayout bug solution
    return cell
}

All seems okay, but UITableViewCell don't resize when image is loaded and I am trying to reload cell at index path.
Interesting moment, that it will work if I scroll down and then come back to cell.
I have similar error before and I fixed it reading this article UITableView layout messing up on push segue and return. (iOS 8, Xcode beta 5, Swift) , third answer. But it didn't help me now. Looks like I need to call some method to recalculate UITableViewCell, but I don't understand what.

Community
  • 1
  • 1
  • wrap the `.reloadRows...` call between `self.table.beginUpdates()` and `self.table.endUpdates()`. – Sulthan May 11 '15 at 13:53

2 Answers2

1

First question : Change UIImageView view mode from Scale to Fill to Aspect Fit (in storyboad)

Second question : Remove dispatch async if image is not nil and make you code look similar like this:

if( image == nil ) {
...
}
else {
    cell.img.image = image       
}
Zell B.
  • 10,266
  • 3
  • 40
  • 49
  • Thx! Second question is closed. About "Aspect Fit", I was trying this, but i was getting strange blank space ( http://i.stack.imgur.com/MkynK.png ), do you know what it can be? It is not constrains = 12. Anyway, thx again! – Максим Панич May 11 '15 at 13:06
  • Now check the clip subviews checkbox in storyboard for your uimageview and tell me if thats the desired result – Zell B. May 11 '15 at 13:24
0

For first one in the storyboard select the image view and click on the pin icon for setting auto layout constraint and check width and height. it will remain the width and height constant.

Krishna Verma
  • 814
  • 2
  • 8
  • 23