Ios 如何使UITableViewCell适应整个TextView,而不考虑文本的大小?
Ios 如何使UITableViewCell适应整个TextView,而不考虑文本的大小?,ios,xcode,swift,uitableview,Ios,Xcode,Swift,Uitableview,我试图在每个表格单元格中显示一个文本字段。问题是我似乎无法使UITableViewCell足够高,以适应整个TextView。UITableViewCell不需要是动态的,因为数据是在视图加载时加载到UITextView中的。以下是我的代码: // // chatViewController.swift // collaboration // // Created by nick on 11/21/15. // Copyright © 2015 Supreme Leader. All r
我试图在每个表格单元格中显示一个文本字段。问题是我似乎无法使UITableViewCell足够高,以适应整个TextView。UITableViewCell不需要是动态的,因为数据是在视图加载时加载到UITextView中的。
以下是我的代码:
//
// chatViewController.swift
// collaboration
//
// Created by nick on 11/21/15.
// Copyright © 2015 Supreme Leader. All rights reserved.
//
import UIKit
class chatViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var testLabel: UILabel!
var messages: NSMutableArray = NSMutableArray()
var authors: NSMutableArray = NSMutableArray()
func tableView(tableView: UITableView, numberOfRowsInSection Section: Int) -> Int {
return self.authors.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! chatTableViewCell
cell.authorLabel?.text = self.authors.objectAtIndex(indexPath.row) as? String
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
let receivedUsername = NSUserDefaults.standardUserDefaults().stringForKey("usernameToMessageWith")
testLabel.text = "\(receivedUsername! as String)"
authors.addObject("")
authors.addObject("You:")
CGRect frame = messagesTextView.frame;
frame.size = messagesTextView.contentSize;
messagesTextView.frame = frame;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
我完全不知道该怎么做。请不要取笑我可怜的错误的范围尝试。如果您使用文本字段,您必须通过编程计算高度,并在显示单元格时设置高度。但是,如果它不可编辑,则可以使用UILabel执行以下操作 在您的
viewdiload
settableView.estimatedroweight=
和tableView.rowHeight=UITableViewAutomaticDimension
然后,在自定义单元格中,需要设置UILabel顶部和底部朝向contentView边缘的布局约束,并将UILabels行设置为0
textfield可能的解决方法:
同时使用文本字段和UILabel,并将UILabels文本颜色设置为“清除颜色”。通过这种方式,您可以使用UILabel调整高度,但仍然具有文本字段的功能。代码
tableView.estimatedRowHeight = <expected height>
tableView.rowHeight = UITableViewAutomaticDimension
假设标签的顶部和底部约束分别为10和10,则返回语句如下:
return label.frame.height + 20
在heightforrowatinex中调用此方法,并将文本作为参数传递给该方法。它将根据计算结果返回动态高度
编辑
如何使用
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return requiredHeight("Your text")
}
如果文本不可编辑,请使用UILabel。非常感谢您的帮助,您的函数看起来很有潜力。我很少在谷歌上搜索,也找不到任何关于如何使用HeightForRowatinex方法的信息。我是否只是将HeightForRowatinex(requiredHeightVar)放在viewDidLoad()或tableView方法中?感谢您将此方法放入tableView的HeightForRowatinex中,如func tableView(tableView:UITableView,heightForRowAtIndexPath:NSIndexPath)->CGFloat{return requiredHeight(“要显示的动态文本”)}
heightForRowAtIndexPath是需要在视图控制器类中使用的tableView数据源方法。检查编辑的答案
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return requiredHeight("Your text")
}