夫特3 &的Xcode 8.3.2
使用的UILabel代替UITextView的,并设置numberOfLine = 0,所以它会根据其内容自动调整大小
或者
如果你想保留UITextView而不是UILabe L,这里是代码
class YourClass: UITableViewController, UITextViewDelegate {
var yourCustomCell: UITableViewCell = UITableViewCell()
override func viewDidLoad() {
super.viewDidLoad()
table.estimatedRowHeight = 40.0 // Replace with your actual estimation
table.rowHeight = UITableViewAutomaticDimension
// Tap to dismiss keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EditInfoViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// Add tableView delegate
tableView.dataSource = self
tableView.delegate = self
// Add textView delegate
yourTextView.delegate = self
}
// Text view delegate, dont forget to add yourTextView.delegate = self in viewDidLoad
func textViewDidChange(_ textView: UITextView) {
if textView == yourTextView {
let newHeight = yourCustomCell.frame.size.height + textView.contentSize.height
yourCustomCell.frame.size.height = newHeight
updateTableViewContentOffsetForTextView()
}
}
// Animate cell, the cell frame will follow textView content
func updateTableViewContentOffsetForTextView() {
let currentOffset = tableView.contentOffset
UIView.setAnimationsEnabled(false)
tableView.beginUpdates()
tableView.endUpdates()
UIView.setAnimationsEnabled(true)
tableView.setContentOffset(currentOffset, animated: false)
}
// UITableViewDelegate, UITableViewDataSource
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = yourCustomCell
cell.selectionStyle = .none
return cell
}
}
其结果是在这里:使用textViewDelegate,和自定义缩放功能
后
结果,我不知道如何做一个标签edditable所以我去做textView调整大小。我不确定我做错了什么。这是我如何设置textView的代表: titleTextView.delegate = self as? UITextViewDelegate – alvarlagerlof
@Ideaman在你的viewDidLoad声明这个“titleTextView.deleget = self”,并在yourClass中添加这个类myViewController:UIViewController,UITextViewDelegate {} –
它希望我把它转换到UITextViewDelegate – alvarlagerlof