Получить изображение ячейки из UICollectionView в Swift 4 - PullRequest
0 голосов
/ 02 ноября 2018

Я создал UICollectionView и создал пользовательскую ячейку.

Я поместил изображение в пользовательскую ячейку и вернул ячейку.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as? HomeCollectionViewCell,
    let arts = self.artList else { return HomeCollectionViewCell() }

    if arts.count > indexPath.row
    {
        let model = arts[indexPath.row]

        cell.imgView.sd_setImage(with: URLHelper.createEncodedURL(url: model.url), completed: nil) // set cell image
    }

    return cell
}

Затем мы выполняем функцию, которая устанавливает вертикальный размер ячейки.

func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat
{
    // get cell information

    return // cell Image Height
}

Однако я не знаю, как получить информацию о ячейке (вертикальное значение ячейки) из этой функции.

Что мне делать?

Ответы [ 6 ]

0 голосов
/ 02 ноября 2018

Поскольку изображение внутри модели необходимо повторно использовать в , следуя методам , поэтому загрузите его в самой модели с остальными данными из службы API.

func collectionView(collectionView: UICollectionView,
                    heightForImageAtIndexPath indexPath: IndexPath,
                    withWidth: CGFloat) -> CGFloat

&

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

Код для скачивания изображения в модели:

if let url = URL(string: "image_url_string") {
    if let data = try? Data(contentsOf: url) {
        image = UIImage(data: data)
    }
}

В viewController PinterestLayoutDelegate:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as? HomeCollectionViewCell,
        let arts = self.artList else { return HomeCollectionViewCell() }

    if arts.count > indexPath.row {
        let model = arts[indexPath.row]

        cell.imgView.image = model.image //Which is downloaded in the model itself.
    }

    return cell
}

func collectionView(collectionView: UICollectionView, heightForImageAtIndexPath indexPath: IndexPath, withWidth: CGFloat) -> CGFloat {

    // get image information
    let image = self.artList[indexPath.item].image

    return image.height(forWidth: withWidth) // cell Image Height
}

И не забудьте использовать это расширение:

public extension UIImage {
    public func height(forWidth width: CGFloat) -> CGFloat {
        let boundingRect = CGRect( x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
        let rect = AVMakeRect(aspectRatio: size, insideRect: boundingRect)
        return rect.size.height
    }
}
0 голосов
/ 02 ноября 2018

Я думаю, что вы можете решить эту проблему, создав публичный массив ваших ячеек, а затем добавив каждую ячейку в массив непосредственно перед тем, как вы вернете ячейку ...

там вы можете получить массив созданных ячеек и получить любую информацию, связанную с созданными ячейками, проверив массив ячеек. Надеюсь, это поможет

 var cellArray : [HomeCollectionViewCell] = [HomeCollectionViewCell]()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as? HomeCollectionViewCell,
let arts = self.artList else { return HomeCollectionViewCell() }

if arts.count > indexPath.row
{
    let model = arts[indexPath.row]

    cell.imgView.sd_setImage(with: URLHelper.createEncodedURL(url: model.url), completed: nil) // set cell image
}
self.cellArray.append(cell)
return cell
}
0 голосов
/ 02 ноября 2018

Вы можете получить информацию о ячейке, как показано ниже.

func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat
{
    // get cell information

    if let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionViewCell{

        let image = cell.imgView.image

        return min(image.size.height, 300.0) // cell Image Height
    }


    return 0// cell Image Height
}
0 голосов
/ 02 ноября 2018

Вы можете использовать guard-let здесь.

func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat {

  guard let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionViewCell else { 
   return 0
  }

  //do something with cell
  return 80//calculate height of cell
}
0 голосов
/ 02 ноября 2018

Используйте это, чтобы получить ячейку.

let cell = collectionView.cellForItem(at: indexPath)

Но не уверен, зачем вам клетка здесь. Если вам нужна ячейка с динамической высотой, это вообще не нужно, вы должны использовать autolayout

0 голосов
/ 02 ноября 2018

Вы можете сделать это так:

if let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionViewCell { 
    return cell.imgView.frame.height
}
return 0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...