Create UITableView programmatically in iOS Swift (Table height not auto resizing)

眉间皱痕 提交于 2020-01-24 20:47:40

问题


I know there are lot of similar questions. But, there isn't a proper answer for my problem. I need to create Custom UITableView programmatically - Not using drag and drop at all. Just swift code. I have already done almost everything except one thing is not working.

Custom TableView Cell looks like this

    ---------------------------------
    -------
    | Pic |  Name
    |     |  Profession
    -------
    Multi-line text here (title)

    Multi-line text here again that
    will have more description of
    what is written above

    List of all phone numbers,
    multi-line again - multiple phone
    numbers

    footer
    ----------------------------------

I have succeeded in everything except the auto-resizing of Table cell height is not working. I want to accomplish this programmatically and so facing problem. Also, I don't have much experience in iOS programming.

This is the pattern I arrived at after reading many stackoverflow answers and other sources.

Model

class Model {
    // members

    init(..) {
        // members initialized
    }
}

CustomCell

class CustomCell: UITableViewCell {
    // cell members, fields

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        // all fields initialized
    }

    override func prepareForReuse() {
        super.prepareForReuse()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.updateConstraints()
    }

    func autoAdjustTextView(textView: UITextView) {
        textView.scrollEnabled = false  // this is important
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        textView.frame = newFrame
    }

    override func updateConstraints() {
        super.updateConstraints()

        // set AutoLayout constraints using Cartography
        autoAdjustTextView(descriptionMultiLineText)
        autoAdjustTextView(titleMultiLineText)
        autoAdjustTextView(phoneNumberMultiLineText)

        constrain(background) { background in
            background.top == background.superview!.top
            background.left == background.superview!.left
            background.right == background.superview!.right
    //            background.height == CELL_HEIGHT
        }

        constrain(background, iconContainerView) { background, iconContainerView in
            iconContainerView.left == background.left + CustomSizes.PADDING
            iconContainerView.top == background.top + CustomSizes.PADDING
        }

        constrain(background, textIconLabel, userNameLabel) { background, imageLabel, nameLabel in
            nameLabel.left == imageLabel.right + CustomSizes.PADDING
            nameLabel.top == imageLabel.top
        }

        constrain(background, userNameLabel, professionLabel) { background, nameLabel, label in
            label.left == nameLabel.left
            label.top == nameLabel.bottom + CustomSizes.PADDING_SMALL
        }

        constrain(background, professionLabel, updatedAtLabel) { background, professionLabel, label in
            label.left == professionLabel.right + CustomSizes.PADDING
            label.top == professionLabel.top
        }

        constrain(titleMultiLineText, background, professionLabel) { titleMultiLineText, background, professionLabel in
            titleMultiLineText.left == background.left + CustomSizes.PADDING
            titleMultiLineText.right == background.right - CustomSizes.PADDING
            titleMultiLineText.top == professionLabel.bottom + CustomSizes.PADDING_SMALL
        }

        constrain(descriptionMultiLineText, background, titleMultiLineText) { descriptionMultiLineText, background, titleMultiLineText in
            descriptionMultiLineText.left == background.left + CustomSizes.PADDING
            descriptionMultiLineText.right == background.right - CustomSizes.PADDING
            descriptionMultiLineText.top == titleMultiLineText.bottom
        }

        constrain(phoneNumberMultiLineText, background, descriptionMultiLineText) { phoneNumberMultiLineText, background, descriptionMultiLineText in
            phoneNumberMultiLineText.left == background.left + CustomSizes.PADDING
            phoneNumberMultiLineText.right == background.right - CustomSizes.PADDING
            phoneNumberMultiLineText.top == descriptionMultiLineText.bottom
        }

        // more constraints for some icons on a single line below the phone number multi line field



        didSetupConstraints = true
    }
}

ViewController

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // members and variables

    init() {
        super.init(nibName: nil, bundle: nil)
        print("init()")
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()
        // show loading
        self.setUpView(true)
    }

    func setUpView(isFirstTime: Bool) {
        // load data from network

        if isFirstTime {
            self.setupTableView()
            self.addConstraints()
        } else {
            self.tableView.reloadData()
        }
    }

    func setupTableView() {
        self.tableView = UITableView(frame: view.bounds, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .None
        tableView.registerClass(CustomCell.self, forCellReuseIdentifier: NSStringFromClass(CustomCell))
        tableView.scrollEnabled = true

        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension

        self.view.addSubview(tableView)
    }

    func addConstraintsForView() {
        constrain(self.view, tableView) { view, tableView in
            tableView.top == view.top
            tableView.left == view.left
            tableView.right == view.right
            tableView.bottom == view.bottom
        }
    }

    // other tableView methods implemented

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

    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.All
    }
}

What should I do now ? or is there any better method ?

来源:https://stackoverflow.com/questions/39195116/create-uitableview-programmatically-in-ios-swift-table-height-not-auto-resizing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!