iOS开发 - TableView 头视图实现下拉添加
2016-08-23 本文已影响701人
小黑Swift
简单使用TableView的头视图实现下拉添加
原理很简单,下拉时候增加头视图,输入完成后,移除
Untitled.gifclass TableViewController: UITableViewController,UITextFieldDelegate {
var TestData = [String]()
var textField: UITextField! {
let textField = UITextField(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
textField.textAlignment = .Center
textField.placeholder = "输入新的项目"
textField.becomeFirstResponder()
textField.delegate = self
return textField
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor(red: 245/255, green: 254/255, blue: 255/255, alpha: 1)
let tapGestureRecongizer = UITapGestureRecognizer(target: self, action: #selector(TableViewController.hideTextField))
tapGestureRecongizer.cancelsTouchesInView = false //点击继续传递到下层,防止Cell无法点击
self.tableView.addGestureRecognizer(tapGestureRecongizer)
}
func hideTextField() {
textField.resignFirstResponder()
UIView.animateWithDuration(0.5, animations: {
self.tableView.tableHeaderView = nil
}) { (finished) in
self.tableView.reloadData()
}
}
//MARK: 原理 -> 下拉显示头视图 -> 输入完成 —> 收回键盘 -> 移除头视图
override func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
if scrollView.contentOffset.y < -88 {
tableView.tableHeaderView = textField
tableView.tableHeaderView?.alpha = 0
UIView.animateWithDuration(1, animations: {
self.tableView.tableHeaderView?.alpha = 1
})
}
}
// MARK: - TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
TestData.append(textField.text!)
hideTextField()
return true
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TestData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(String(UITableViewCell), forIndexPath: indexPath)
cell.textLabel?.text = TestData.reverse()[indexPath.row]
return cell
}
}