根据UITableView Swift中的文本大小扩展标签/单元格大小

Kal*_*asi 8 uitableview ios swift

我是iOS开发的新手.我的细胞大小有问题.我没有使用Auto-Laylout功能.我目前的TableView细胞看起来像这样.我想使图像中选择的标签大小根据该标签的文本内容动态扩展.

提前致谢.

Sha*_* BS 13

我认为像下面的快速版本,它计算更接近的值,而不是精确的高度,例如

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

 var messageArray:[String] = []
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
      messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background",
                      "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.",
                      " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.",
                      "Whale&W",
                      "Rcokey",
                      "Punch",
                      "See & Dive"]
}
Run Code Online (Sandbox Code Playgroud)

在上面我们有一个包含不同长度的字符串的数组

 func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1;
    }

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return messageArray.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell;
    if(cell == nil)
    {
        cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "CELL")
        cell?.selectionStyle = UITableViewCellSelectionStyle.none
    }
    cell?.textLabel.font = UIFont.systemFontOfSize(15.0)
    cell?.textLabel.sizeToFit()
    cell?.textLabel.text = messageArray[indexPath.row]
    cell?.textLabel.numberOfLines = 0
    return cell!;
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row])
    return height + 70.0
}

func calculateHeight(inString:String) -> CGFloat
{
    let messageString = inString
    let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]

    let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

    let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

    let requredSize:CGRect = rect
    return requredSize.height
}
Run Code Online (Sandbox Code Playgroud)

在新项目中尝试它只需添加tableview并设置其数据源并委托并通过上面的代码并运行

结果如下

在此输入图像描述


sta*_*hop 6

尝试覆盖方法:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

完整解决方案

在iOS 8中,Apple为UITableView引入了一项名为Self Sizing Cells的新功能.在iOS 8之前,如果在具有不同行的表视图中显示动态内容,则需要自行计算行高.

总之,以下是使用自定义单元格时要实现的步骤:

•在原型单元格中添加自动布局约束

•指定表视图的estimatedRowHeight

•将表视图的rowHeight设置为UITableViewAutomaticDimension

在代码中表达最后两点,它看起来像:

tableView.estimatedRowHeight = 43.0;
tableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)

您应该在viewDidLoad方法中添加它.

只需两行代码,您可以指示表视图计算与其内容匹配的单元格大小并动态呈现它.这种自定义单元格功能可以节省大量的代码和时间.

在UILabel的Attributes Inspector中,将Lines值更改为0,因此label将自动调整行数以适合内容.

请注意,第一点是必需的,请记住,如果不应用自动布局,则无法使用自定义单元格.

如果您熟悉汽车布局,请阅读此内容,这就足够了:

https://developer.apple.com/library/mac/recipes/xcode_help-IB_auto_layout/chapters/pin-constraints.html

或者,要设置自动布局,但也许不是什么你到底期望更简单的方法是清除所有的约束条件,去解决自动布局问题,并为所有视图点击重置为建议的约束.