Добрый день! У меня есть 2 проблемы, и я надеюсь, что вы мне поможете.Autolayout, async загрузить изображение в uiimageview (Swift, xCode6)
1) У меня есть лента новостей в моем приложении, которая содержит изображения. Я использую Autolayout для динамических ячеек:
, и я хочу, чтобы образ, чтобы сохранить свое отношение и полностью заполнить ширину ячейки (с margins = 12
). я поставил Сдерживает, клетка autoresizable, но изображение не спасло его соотношение:
.
Что я делаю неправильно?
2) Вторая проблема, я загружать изображения асинхронно, вот мой код:
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
}
Все кажется хорошо, но UITableViewCell
не менять размеры при загрузке изображения, и я пытаюсь перезагрузить ячейку с индексом дорожка.
Интересный момент, что он будет работать, если я прокручу вниз, а затем вернусь в камеру.
У меня есть аналогичная ошибка, прежде чем я исправил ее, прочитав эту статью UITableView layout messing up on push segue and return. (iOS 8, Xcode beta 5, Swift), третий ответ. Но это не помогло мне сейчас. Похоже, мне нужно вызвать какой-то метод для пересчета UITableViewCell
, но я не понимаю, что.
заверните вызов '.reloadRows ...' между 'self.table.beginUpdates()' и 'self.table.endUpdates()'. – Sulthan