2016-04-28 2 views
10

Я могу расширять и сворачивать ячейки, но я хочу вызвать функции (развернуть и свернуть) внутри UITableViewCell, чтобы изменить название кнопки.Развернуть и свернуть ячейки tableview

Iphone 5

 
import UIKit 

class MyTicketsTableViewController: UITableViewController { 

    var selectedIndexPath: NSIndexPath? 
    var extraHeight: CGFloat = 100 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 5 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTicketsTableViewCell 
     return cell 
    } 

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     if(selectedIndexPath != nil && indexPath.compare(selectedIndexPath!) == NSComparisonResult.OrderedSame) { 
      return 230 + extraHeight 
     } 

     return 230.0 
    } 

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     if(selectedIndexPath == indexPath) { 
      selectedIndexPath = nil 
     } else { 
      selectedIndexPath = indexPath 
     } 

     tableView.beginUpdates() 
     tableView.endUpdates() 
    } 
} 

 
import UIKit 

class MyTicketsTableViewCell: UITableViewCell { 

    @IBOutlet weak var expandButton: ExpandButton! 
    @IBOutlet weak var detailsHeightConstraint: NSLayoutConstraint! 

    var defaultHeight: CGFloat! 

    override func awakeFromNib() { 
     super.awakeFromNib() 

     defaultHeight = detailsHeightConstraint.constant 

     expandButton.button.setTitle("TAP FOR DETAILS", forState: .Normal) 
     detailsHeightConstraint.constant = 30 
    } 

    func expand() { 
     UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { 
      self.expandButton.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 0.99)) 
      self.detailsHeightConstraint.constant = self.defaultHeight 
      self.layoutIfNeeded() 

      }, completion: { finished in 
       self.expandButton.button.setTitle("CLOSE", forState: .Normal) 
     }) 
    } 

    func collapse() { 
     UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { 
      self.expandButton.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 0.0)) 
      self.detailsHeightConstraint.constant = CGFloat(30.0) 
      self.layoutIfNeeded() 

      }, completion: { finished in 
       self.expandButton.button.setTitle("TAP FOR DETAILS", forState: .Normal) 
     }) 
    } 

} 

+0

Пожалуйста, проверьте это решение: [введите описание ссылки здесь] (https://stackoverflow.com/questions/21396907/how-to-programmatically-increase-uitableview-cells-height-in-iphone/45424594# 45424594) –

ответ

12

Если вы хотите, чтобы клетка, чтобы получить физически больше, то где у вас есть магазин NSIndexPath, в heightForRow: использования:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    if selectedIndexPath == indexPath { 
     return 230 + extraHeight 
    } 
    return 230.0 
} 

Затем, когда вы хотите расширить один в didSelectRow:

storedIndexPath = indexPath 
tableView.beginUpdates 
tableView.endUpdates 

Редактировать

Это заставит клетки анимировать сами становятся все больше, вы не нужны дополнительные анимационные блоки в клетке.

Edit 2

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     if(selectedIndexPath == indexPath) { 
      selectedIndexPath = nil 

      if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MyTicketsTableViewCell { 
      cell.collapse() 
      } 
      if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:indexPath.row+1, section: indexPath.section) as? MyTicketsTableViewCell { 
      cell.collapse() 
      } 
     } else { 
      selectedIndexPath = indexPath 

      if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MyTicketsTableViewCell { 
       cell.expand() 
      } 

      if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:indexPath.row+1, section: indexPath.section) as? MyTicketsTableViewCell { 
      cell.expand() 
      } 
     } 

     tableView.beginUpdates() 
     tableView.endUpdates() 
    } 
+0

Я могу свернуть и расширить ячейку, как вы сказали. Но я хочу изменить название кнопки внутри ячейки, так как я могу вызвать функцию внутри ячейки. –

+0

, пожалуйста, проверьте edit2: – SeanLintern88

+0

Функция вызова двух ячеек. Я имею в виду, когда я нажимаю одну ячейку, две ячейки расширяют функции :( –

2

Все, что вам нужно реализовать UITableView Делегат таким образом:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

По умолчанию estimatedHeight является CGRectZero, когда вы устанавливаете какое-то значение для него, она позволяет автоматического изменения (такая же ситуация с UICollectionView), вы можете сделать и так:

tableView?.estimatedRowHeight = CGSizeMake(50.f, 50.f); 

Затем вам нужно настроить ограничения внутри вашей ячейки.

Проверить этот пост: https://www.hackingwithswift.com/read/32/2/automatically-resizing-uitableviewcells-with-dynamic-type-and-ns

Надеется, что это помогает)

+0

Это должен быть комментарий. –

+0

Использование UITableViewAutomaticDimension для оценкиHeight поражает всю цель с использованием оценочного критерия в первую очередь - он будет называть автоматический макет на каждом indexPath в вашем tableView для вычисления высоты всего содержимого, вместо использования автоматического макета только для видимых ячеек и для оценкиHeight (что в идеале намного быстрее для вычисления) для всех невидимых indexPaths. –

1

В MyTicketsTableViewController классе, внутри cellForRowAtIndexPath метода источника данных добавить цель для кнопки.

cell.expandButton.addTarget(self, action: "expandorcollapsed:", forControlEvents: UIControlEvents.TouchUpInside) 
+0

Я не понимаю, для чего это необходимо? –

+0

ваши вызовы расширяют и сворачивают методы в классе tableviewcell. Вместо этого в вашем контроллере tableview объявляют метод expand, collapse и в вызове cellForRowAtIndexPath такой метод – Jeyamahesan

Смежные вопросы