Swift中的Self Sizing Cell,如何以编程方式进行约束?

时间:2014-12-09 00:58:36

标签: ios uitableview swift ios8 sidebar

我试图用快速自我调整单元格做侧边栏。我找到了这个很棒的教程:http://www.appcoda.com/self-sizing-cells/

据我所知,你需要做3件事来制作一个自定型单元格:

  1. 为原型单元定义自动布局约束
  2. 指定表格视图的estimatedRowHeight
  3. 将表视图的rowHeight设置为UITableViewAutomaticDimension
  4. 最后两个在代码中涵盖在教程中,但第一个是由故事板解释的,我的问题是如何通过代码实现它?

    我有这个方法,我得到我的自定义单元格,我认为我必须在这里实现约束(在教程中你可以看到什么样的约束)但我不知道如何,所以请你能给我一些帮助?

    override func tableView(tableView: (UITableView!),   cellForRowAtIndexPath indexPath: (NSIndexPath!)) -> UITableViewCell{ 
    
     if cell == nil {
    
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CellId")
    
        cell!.backgroundColor = UIColor.clearColor()
        cell!.textLabel?.textColor = UIColor.darkTextColor()
    
            let selectedView:UIView = UIView(frame:CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
            selectedView.backgroundColor = UIColor.orangeColor().colorWithAlphaComponent(0.3)
    
    
        cell!.selectedBackgroundView = selectedView
    
        //asignar valores a la celda
    
        cell!.textLabel?.text = tableData[indexPath.row]
    
        cell!.textLabel?.numberOfLines = 0
    
        cell!.setTranslatesAutoresizingMaskIntoConstraints(false)
    
    
    
                       }
    
        return cell!
    
    
       }
    

    更新1:   The text goes beyond the 3rd break of line un the 1st an 3rd row

    文本超出了第1行和第3行的第3行,但这里只显示最大值。 3个分界线

    谢谢!

3 个答案:

答案 0 :(得分:1)

我找到了一个很好的功能来制作细胞动态大小

func dynamicHeight(text:String, font:UIFont, width:CGFloat) -> CGFloat{
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping

        label.font = font
        label.text = text

        label.sizeToFit()
        return label.frame.height

    }

在heightForRowAtIndexPath

中调用此函数

我希望它有效。

答案 1 :(得分:0)

不要在tableView(_:cellForRowAtIndexPath:)中添加布局限制。

您不应该自己在该方法中实例化表格视图单元格。相反,您应该使用UITableView注册一个(可能在视图控制器的viewDidLoad()方法中)(registerClass(_:forCellReuseIdentifier:)registerNib(_:forCellReuseIdentifier:))。

tableView(_:cellForRowAtIndexPath:)中,您使用dequeueReusableCellWithIdentifier(_:forIndexPath:)来获取单元格的实例。表格视图将在您滚动时重复使用单元格,因此它不必始终创建新单元格。从本质上讲,让我们说你不会同时在屏幕上看到超过15个单元格,然后不会超过那么多实例。

现在,当您注册表视图单元格(参见上文)时,您可能应该继承UITableViewCell,然后在代码中设置布局约束(可能会覆盖init(style:reuseIdentifier:)),或者您可以创建.nib文件并使用它。然后,您可以通过图形用户界面在Xcode中设置约束。

如果您有任何问题,请与我们联系。

答案 2 :(得分:0)

试试这个: -

首先在你的班级中添加这两个功能

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

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

其次,为了使UITableViewAutomaticDimension工作,请确保已添加相对于单元格容器视图的所有左,右,底部和顶部约束。

相关问题