具有可变单元格高度的UITableView:在IB中工作但不是以编程方式工作

Sur*_*gch 25 uitableview ios swift mongolian-vertical-script

TL; DR

我以编程方式创建的表格视图单元格未根据其自定义视图的内在内容高度进行大小调整,即使我正在使用UITableViewAutomaticDimension并设置顶部和底部约束.

问题可能在于我的UITableViewCell子类实现.请参阅下面的代码"无法以编程方式工作">"代码">"MyCustomCell.swift".

目标

我正在尝试为自定义蒙古语键盘制作一个建议栏.蒙古文是垂直写的.在Android中它看起来像这样:

在此输入图像描述

进展

我已经知道我应该使用一个UITableView可变单元格高度,从iOS 8开始可以使用.这需要使用自动布局并告诉表格视图使用单元格高度的自动尺寸.

我一直在学习的一些事情在我最近的SO问题和答案中有所体现:

所以我已经达到了支持内在内容大小的垂直标签.这些标签放在我的自定义表格视图单元格中.并且如下一节所述,它们在我在故事板中执行时起作用,但在我以编程方式创建所有内容时则不起作用.

在IB工作

为了隔离问题,我创建了两个基本项目:一个用于我使用故事板的地方,另一个用于以编程方式执行所有操作.故事板项目有效.从下图中可以看出,每个表格视图单元格都会调整大小以匹配自定义垂直标签的高度.

在此输入图像描述

在IB

我设置约束来固定顶部和底部以及使标签居中.

在此输入图像描述

ViewController.swift

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let myStrings: [String] = ["a", "bbbbbbb", "cccc", "dddddddddd", "ee"]
    let cellReuseIdentifier = "cell"

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableViewAutomaticDimension
    }

    // number of rows in table view
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.myStrings.count
    }

    // create a cell for each table view row
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
        cell.myCellLabel.text = self.myStrings[indexPath.row]
        return cell
    }

    // method to run when table view cell is tapped
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomCell.swift

import UIKit
class MyCustomCell: UITableViewCell {
    @IBOutlet weak var myCellLabel: UIMongolSingleLineLabel!
}
Run Code Online (Sandbox Code Playgroud)

不能以编程方式工作

由于我希望建议栏成为最终键盘的一部分,因此我需要能够以编程方式创建它.但是,当我尝试以编程方式重新创建上述示例项目时,它无法正常工作.我得到以下结果.

在此输入图像描述

单元格高度未调整大小,自定义垂直标签彼此重叠.

我也收到以下错误:

仅警告一次:检测到约束模糊地建议tableview单元格的内容视图的高度为零的情况.我们正在考虑无意中崩溃并使用标准高度.

在Stack Overflow上多次出现此错误:

然而,大多数人的问题是他们没有同时设置顶部和底部销钉约束.我,或者至少我认为我是,如下面的代码所示.

ViewController.swift

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let myStrings: [String] = ["a", "bbbbbbb", "cccc", "dddddddddd", "ee"]
    let cellReuseIdentifier = "cell"
    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Suggestion bar
        tableView.frame = CGRect(x: 0, y: 20, width: view.bounds.width, height: view.bounds.height)
        tableView.registerClass(MyCustomCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableViewAutomaticDimension
        view.addSubview(tableView)
    }

    // number of rows in table view
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.myStrings.count
    }

    // create a cell for each table view row
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
        cell.myCellLabel.text = self.myStrings[indexPath.row]
        return cell
    }

    // method to run when table view cell is tapped
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomCell.swift

我认为这个问题可能就在这里,因为这是与IB项目的主要区别.

import UIKit
class MyCustomCell: UITableViewCell {

    var myCellLabel = UIMongolSingleLineLabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setup() {
        self.myCellLabel.translatesAutoresizingMaskIntoConstraints = false
        self.myCellLabel.centerText = false
        self.myCellLabel.backgroundColor = UIColor.yellowColor()
        self.addSubview(myCellLabel)

        // Constraints
        // pin top
        NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 0).active = true
        // pin bottom
        NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: 0).active = true
        // center horizontal
        NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true

    }

    override internal class func requiresConstraintBasedLayout() -> Bool {
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)

补充代码

我还将包含我在上述两个项目中使用的自定义垂直标签的代码,但由于IB项目有效,我认为主要问题不在这里.

import UIKit
@IBDesignable
class UIMongolSingleLineLabel: UIView {

    private let textLayer = LabelTextLayer()
    var useMirroredFont = false

    // MARK: Primary input value

    @IBInspectable var text: String = "A" {
        didSet {
            textLayer.displayString = text
            updateTextLayerFrame()
        }
    }

    @IBInspectable var fontSize: CGFloat = 17 {
        didSet {
            updateTextLayerFrame()
        }
    }

    @IBInspectable var centerText: Bool = true {
        didSet {
            updateTextLayerFrame()
        }
    }

    // MARK: - Initialization

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    func setup() {


        // Text layer
        textLayer.backgroundColor = UIColor.yellowColor().CGColor
        textLayer.useMirroredFont = useMirroredFont
        textLayer.contentsScale = UIScreen.mainScreen().scale
        layer.addSublayer(textLayer)

    }

    override func intrinsicContentSize() -> CGSize {
        return textLayer.frame.size
    }

    func updateTextLayerFrame() {

        let myAttribute = [ NSFontAttributeName: UIFont.systemFontOfSize(fontSize) ]
        let attrString = NSMutableAttributedString(string: textLayer.displayString, attributes: myAttribute )
        let size = dimensionsForAttributedString(attrString)

        // This is the frame for the soon-to-be rotated layer
        var x: CGFloat = 0
        var y: CGFloat = 0
        if layer.bounds.width > size.height {
            x = (layer.bounds.width - size.height) / 2
        }
        if centerText {
            y = (layer.bounds.height - size.width) / 2
        }
        textLayer.frame = CGRect(x: x, y: y, width: size.height, height: size.width)
        textLayer.string = attrString
        invalidateIntrinsicContentSize()
    }

    func dimensionsForAttributedString(attrString: NSAttributedString) -> CGSize {

        var ascent: CGFloat = 0
        var descent: CGFloat = 0
        var width: CGFloat = 0
        let line: CTLineRef = CTLineCreateWithAttributedString(attrString)
        width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))

        // make width an even integer for better graphics rendering
        width = ceil(width)
        if Int(width)%2 == 1 {
            width += 1.0
        }

        return CGSize(width: width, height: ceil(ascent+descent))
    }
}

// MARK: - Key Text Layer Class

class LabelTextLayer: CATextLayer {

    // set this to false if not using a mirrored font
    var useMirroredFont = true
    var displayString = ""

    override func drawInContext(ctx: CGContext) {
        // A frame is passed in, in which the frame size is already rotated at the center but the content is not.

        CGContextSaveGState(ctx)

        if useMirroredFont {
            CGContextRotateCTM(ctx, CGFloat(M_PI_2))
            CGContextScaleCTM(ctx, 1.0, -1.0)
        } else {
            CGContextRotateCTM(ctx, CGFloat(M_PI_2))
            CGContextTranslateCTM(ctx, 0, -self.bounds.width)
        }

        super.drawInContext(ctx)
        CGContextRestoreGState(ctx)
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

项目的整个代码都在这里,所以如果有人有兴趣尝试一下,只需创建一个新项目并将上面的代码剪切并粘贴到以下三个文件中:

  • ViewController.swift
  • MyCustomCell.swift
  • UIMongolSingleLineLabel.swift

Sul*_*han 11

错误非常简单:

代替

self.addSubview(myCellLabel)
Run Code Online (Sandbox Code Playgroud)

使用

self.contentView.addSubview(myCellLabel)
Run Code Online (Sandbox Code Playgroud)

另外,我会替换

// pin top
NSLayoutConstraint(...).active = true
// pin bottom
NSLayoutConstraint(...).active = true
// center horizontal
NSLayoutConstraint(...).active = true
Run Code Online (Sandbox Code Playgroud)

let topConstraint = NSLayoutConstraint(...)
let bottomConstraint = NSLayoutConstraint(...)
let centerConstraint = NSLayoutConstraint(...)

self.contentView.addConstraints([topConstraint, bottomConstraint, centerConstraint])
Run Code Online (Sandbox Code Playgroud)

这更明确(您必须指定约束所有者),因此更安全.

问题是,当调用active = true约束时,布局系统必须决定应该添加约束的视图.在你的情况下,因为contentViewmyCellLabel你的第一个共同祖先UITableViewCell,他们被添加到你的UITableViewCell,所以他们实际上并没有约束contentView(约束在兄弟之间不在superview-subview之间).

您的代码实际上触发了控制台警告:

仅警告一次:检测到约束模糊地建议tableview单元格的内容视图的高度为零的情况.我们正在考虑无意中崩溃并使用标准高度.

这使我立即了解为您的标签创建约束的方式.


Tar*_*era 6

我已经测试了你的代码并发现问题在于设置约束,请使用下面的代码部分来设置"MyCustomCell.swift"文件setup()函数中的常量

 let topConstraint = NSLayoutConstraint(item: myCellLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: myCellLabel, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
    let centerConstraint = NSLayoutConstraint(item: myCellLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)
    self.addConstraints([centerConstraint, topConstraint, bottomConstraint])
Run Code Online (Sandbox Code Playgroud)

还可以在"viewcontroller.swift"中将剪辑设置为绑定属性到您的单元格标签

// create a cell for each table view row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
    cell.myCellLabel.text = self.myStrings[indexPath.row]
    cell.myCellLabel.clipsToBounds=true
    return cell
}
Run Code Online (Sandbox Code Playgroud)

为方便起见,我已将示例代码上传到GitHub Dynamic Height Sample

输出现在看起来像这样

在此输入图像描述


归档时间:

查看次数:

1311 次

最近记录:

8 年,10 月 前