Last active
January 13, 2020 14:24
-
-
Save wbbernardes/7bafde074871b979632c3e0d8c3d19d1 to your computer and use it in GitHub Desktop.
tableview expandable header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var selectedIndx = -1 | |
var newIndexSet = IndexSet() | |
var thereIsCellTapped = false | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return 3 | |
} | |
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { | |
return 30 | |
} | |
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { | |
let button = UIButton(type: .system) | |
button.setTitleColor(.darkGray, for: .normal) | |
button.backgroundColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1) | |
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) | |
button.layer.cornerRadius = 5 | |
button.contentHorizontalAlignment = .left | |
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) | |
button.addTarget(self, action: #selector(btnSectionClick(sender:)), for: .touchUpInside) | |
if section == 0 { | |
//adiciona titulo aqui | |
button.setTitle("header 1", for: .normal) | |
} else if section == 1 { | |
button.setTitle("header 2", for: .normal) | |
} else if section == 2 { | |
button.setTitle("header 3", for: .normal) | |
} | |
button.tag = section | |
return button | |
} | |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
if indexPath.section == selectedIndx && thereIsCellTapped{ | |
self.tableView.separatorStyle = .singleLine | |
return 182 | |
}else{ | |
self.tableView.separatorStyle = .none | |
return 4 | |
} | |
} | |
//action when select header | |
@objc func btnSectionClick(sender:UIButton!){ | |
print("selected index",sender.tag) | |
if selectedIndx != sender.tag { | |
self.thereIsCellTapped = true | |
self.selectedIndx = sender.tag | |
newIndexSet = [selectedIndx] | |
if sender.tag == 2 { | |
tableView.separatorStyle = .singleLine | |
} | |
tableView.reloadSections(newIndexSet, with: .fade) | |
} else { | |
// there is no cell selected anymore | |
if sender.tag == 2 { | |
tableView.separatorStyle = .none | |
} | |
self.thereIsCellTapped = false | |
self.selectedIndx = -1 | |
tableView.reloadSections(newIndexSet, with: .fade) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment