在swift 3中子类化的UITableViewCell的contentView总是320点

时间:2018-05-10 07:15:14

标签: ios iphone swift uitableview swift3

我正在尝试在我的子类UITableViewCell中创建一个UILabel,使其成为单元格的整个宽度。但是如果在iPhone 7或7 +中,contentView总是320pt。

代码是:

import UIKit
import SwipeCellKit

class ReuseableCell: SwipeTableViewCell
{
    public var test = UILabel();

    var animator: Any?

    override init(style: UITableViewCellStyle, reuseIdentifier: String!)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier);

        // Always 320pt and I want full width of the table cell
        var width = self.contentView.frame.width;

        test = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: 100));


        test.text = "Lorem ipsum...";

        ...

我被困在这两晚。感谢。

2 个答案:

答案 0 :(得分:2)

您可以尝试自动布局

override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
    super.init(style: style, reuseIdentifier: reuseIdentifier);


    test = UILabel(frame: CGRect.zero);

    self.contentView.addSubview(test)

    test.translatesAutoresizingMaskIntoConstraints = false

    test.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true

    test.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

    test.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true

    test.heightAnchor.constraint(equalToConstant: 200).isActive = true

    test.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true

}

答案 1 :(得分:1)

您必须在override init(style: UITableViewCellStyle, reuseIdentifier: String!)内添加您的标签,但要阅读正确的框架,您已覆盖override func layoutSubviews()并阅读正确的框架