UITextView在Swift中的使用,自适应
如果需要在TableView中使用TextView,一般都是在static cell中用。让输入框自适应,非常简单。
- **使用Autolayout
- **UITextViewDelegate
storyboard
TextView放在中间,设置Constriant,top, bottom,trailing,leading
绑定到VC
下面代码
class MyVC: UITableViewController, UITextViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
}
// MARK: - text view delegate
// autochange the size
func textViewDidChange(textView: UITextView) {
println("\(textView.text)")
tableView.beginUpdates()
tableView.endUpdates()
}
@IBOutlet weak var textView: UITextView! {
didSet {
textView.delegate = self
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 || indexPath.row == 0 {
if self.textView.contentSize.height >= 44 {
return textView.contentSize.height + 20
} else {
return 44
}
} else {
return 0
}
}
OK, Done!
更精准高度和动画,自己慢慢调。