2017-01-20 3 views
3

У меня есть вид коллекции на мой класс (UICollectionView) и класс PostCell (UICollectionViewCell). HomeController имеет всего 4 различных ячейки. У меня также есть кнопка внутри моего PostCell, которая при касании обрабатывает функцию handleChangeSize. Когда я касаюсь этой кнопки, я хочу, чтобы размер определенных ячеек изменился. Предпочтительно изменять высоту, аналогично функции Instagrams «показать больше» на своих ячейках. Любая помощь будет высоко оценена. Спасибо ... Вот мой код:Нажмите кнопку, чтобы изменить размер ячейки UICollectionView.

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { 

     let cellId = "cellId" 

     override func viewDidLoad() { 
      super.viewDidLoad() 
      collectionView?.backgroundColor = UIColor(white: 0.90, alpha: 1.0) 

      collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId) 
      collectionView?.showsVerticalScrollIndicator = false 
      collectionView?.alwaysBounceVertical = true 
     } 

     override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
      return 4 
     } 

     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell 
      return cell 
     } 

     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
      let height = (view.frame.width) * 9/16 
      return CGSize(width: view.frame.width, height: height + 50 + 50) 
    } 
} 

class PostCell: UICollectionViewCell { 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setupViews() 
    } 

    lazy var myButton: UIButton = { 
     let button = UIButton(type: .system) 
     button.setTitle("Change Size", for: .normal) 

     button.addTarget(self, action: #selector(handleChangeSize), for: .touchUpInside) 

     return button 
    }() 

    func handleChangeSize() { 

    } 



    func setupViews() { 
     addSubview(myButton) 

     myButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true 
     myButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
} 

ответ

1

Решение этой проблемы довольно просто. Во-первых, вам нужно указать, какую высоту вы хотите установить для конкретной ячейки, и выполнить это изменение в методе handleChangeSize() (это можно сделать простым frame.size.height = ...).

После этого вам, вероятно, потребуется изменить размер всего вида коллекции, иначе вам предложат неприятные сюрпризы. Выполните расчет (чтобы получить новую высоту) после изменения размера ячейки (вы можете вызвать уведомление или что-то, что срабатывает всякий раз, когда требуется изменение размера).

2

Я сделал это в таблицеView. то же самое для collectionView.

var expandedCells = [Int]() 

вот cellForRowAtIndexPath метод

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "RequestTableViewCell") as! RequestTableViewCell 
    cell.selectionStyle = .none 
    cell.optionButton.tag = indexPath.row 
    cell.optionButton?.addTarget(self, action: #selector(RequestsViewController.deleteAction), for: UIControlEvents.touchUpInside) 
    return cell 
    } 

и действие по кнопке выбора в tableViewCell является

func deleteAction(_ sender: UIButton){ 
    if let button = sender as? UIButton { 
     // If the array contains the button that was pressed, then remove that button from the array 
     if expandedCells.contains(sender.tag) { 
     expandedCells = expandedCells.filter { $0 != sender.tag } 
     } 
     // Otherwise, add the button to the array 
     else { 
     expandedCells.removeAll() 
     expandedCells.append(sender.tag) 
     } 
     // Reload the tableView data anytime a button is pressed 
     self.requestTableView.beginUpdates() 
     self.requestTableView.endUpdates() 

    } 
    } 

и метод heightForRowAtIndexPath является

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    // Set the row height based on whether or not the Int associated with that row is contained in the expandedCells array 
    if expandedCells.contains(indexPath.row) { 
     return 112 
    } else { 
     return 67 
    } 
    } 
+0

Я действительно литий ke идея добавить цель, которая указывает на viewcontroller! –

+0

@BartvanKuik спасибо товарищу .. –

+0

вы спасли меня пару часов, пытаясь найти решение самостоятельно! Большое вам спасибо :) @GaneshKumar – MBH