2016-10-07 2 views
2

Можно ли реализовать расширяемый UITableView с динамической ячейкой прототипа, которая расширяет динамическое число ячеек внутри нее? Нравится:Динамический расширяемый вид таблицы

У меня есть «x» количество курсов в таблицеView. при нажатии на любой курс он расширит «y» количество предметов, восприимчивых к этому курсу.

У меня нет статической ячейки в моем столе. Как я могу это сделать?

+1

См следующую ссылку: http://stackoverflow.com/questions/11626028/expandable-tableview-in-iphone – KKRocks

+0

Сделать 'numberOfSection' к ** course.count ** , Каждый раздел содержит одну строку по умолчанию ** (т. Е.) Название курса **. В 'didSelect' сохранить какое-то значение« BOOL »в зависимости от того, что увеличивает число« numberOfRows »в этом конкретном разделе на ** Subject.count ** и перезагрузите таблицу – Gokul

+0

Я предлагаю использовать [эту библиотеку] (https://github.com/ujell/YUTableView-Swift), я попробовал, и это сработало для меня. Кроме того, он поддерживает Swift 3. –

ответ

0

Вот простой и полный код для расширяемых Tableview клеток Я использую

@IBOutlet weak var tableView: UITableView! 
struct Data { 
    var title = "" 
    var categories = [String]() 
    var isSelected = false 

    init(title: String, categories: [String]) { 
     self.title = title 
     self.categories = categories 
    } 
} 


var tableData = [Data]() 

override func viewDidLoad() { 

    tableData.append(Data(title: "Click Me", categories: ["Row 1", "Row 2", "Row 3"])); 
    tableData.append(Data(title: "Click Me", categories: ["Row 1", "Row 2", "Row 3"])); 
    tableData.append(Data(title: "Click Me", categories: ["Row 1", "Row 2", "Row 3"])); 
    tableData.append(Data(title: "Click Me", categories: ["Row 1", "Row 2", "Row 3"])); 


    super.viewDidLoad() 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 3 
} 
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let viewHeader = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 50)) 
    viewHeader.backgroundColor = UIColor.whiteColor() 

    let titleLabel = UILabel(frame: CGRectMake(10, 0, self.view.frame.width - 10, 50)) 
    titleLabel.text = tableData[section].title 
    viewHeader.addSubview(titleLabel) 


    let btn = UIButton(frame: CGRectMake(0, 0, self.view.frame.width, 50)) 
    btn.addTarget(self, action: #selector(ViewController.headerDidSelect(_:)), forControlEvents: .TouchUpInside) 
    btn.tag = section 
    viewHeader.addSubview(btn) 

    return viewHeader 
} 
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return tableData[section].isSelected ? tableData[section].categories.count : 0 
} 
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 
    cell.textLabel?.text = tableData[indexPath.section].categories[indexPath.row] 
    return cell 
} 


func headerDidSelect(sender: UIButton) { 
    for i in 0..<tableData.count { 
     if tableData[i].isSelected == true { 
      tableData[i].isSelected = false 
      tableView.reloadSections(NSIndexSet(index: i), withRowAnimation: .Fade) 
      if i == sender.tag { 
       return 
      } 
      break 
     } 
    } 
    tableData[sender.tag].isSelected = true 
    tableView.reloadSections(NSIndexSet(index: sender.tag), withRowAnimation: .Fade) 
} 
1

Вы можете использовать ExpyTableView, что делает расширяющийся участок от вашей данной ячейки заголовка. Совместимость с iOS 8.0.

Все, что вам нужно сделать, это импортировать ExpyTableView, а затем:

class ViewController: ExpyTableViewDataSource, ExpyTableViewDelegate { 

    @IBOutlet weak var expandableTableView: ExpyTableView! 

    // First, set data source and delegate for your table view. 
    override func viewDidLoad() { 
    super.viewDidLoad() 
    expandableTableView.dataSource = self 
    //expandableTableView.delegate = self 
    } 

    // Then return your expandable cell instance from expandingCell data source method. 
    func expandableCell(forSection section: Int, inTableView tableView: ExpyTableView) -> UITableViewCell { 
    // this cell will be displayed at IndexPath with section: section and row 0 
    } 
} 

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

В примере проекта есть конкретный пример, который соответствует вашим потребностям. Вы просто добавить этот код:

func numberOfSections(in tableView: UITableView) -> Int { 
     return x //x is your provided number here.(e.g. number of courses) 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return y //y is your provided number here.(number of subjects related to a course) 
    } 
Смежные вопросы