简体   繁体   中英

How to set the auto layout constraints for tableviewcell

I need to set the leading and trailing for the UITableViewCell which is under UITableViewController.

Specific class for the UITableViewCell , I have added below code.

 override func layoutSubviews() {
        self.frame = CGRect(x: 10.0, y:  self.frame.origin.y, width: 390.0, height: self.frame.size.height)
        super.layoutSubviews()
    }

The above leaves spaces in leading and trailing. But the problem when i tested in iPhone 5s and 4 simulator it leads to horizontal scrolling.

I taught the problem due to the constant width. So I have got specific label field width from the UITableViewcell and subtracted by 10.0

I have tried the below code for the width issue. But , Nothing worked out.

func setFrame(x: CGFloat, y: CGFloat , width: CGFloat , height: CGFloat ) {
        let newX = x.isNaN ? self.frame.origin.x : x
        let newY = y.isNaN ? self.frame.origin.y : y
        let newWidth = width.isNaN ? self.bounds.size.width : width
        let newHeight = height.isNaN ? self.bounds.size.height : height

        self.frame = CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
    }
    override func layoutSubviews() {
        let width = (greetingLabel.bounds.size.width - 10.0)
        setFrame(x: 5.0, y: 5.0, width:width, height: self.frame.height)
    }

I have tried keeping all the fields inside View, but the UI doesn't look good.

Please provide me some input how set the leading and trailing for the UITableViewCell.

I want to achieve like this screen:

在此处输入图片说明

enter image description here

In your case, I would make cell's contentView transparent ( contentView.backgroundColor = .clear ). Then I would add a new property to the cell, let us call it newContentView , add it to the contentView , and use constraints to fit it as far from the edges as you want. Then just use newContentView as the space to which you want to add your content.

class CustomCell: UITableViewCell {
    fileprivate let newContentView = UIView()

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

        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear

        self.contentView.addSubview(newContentView)
        newContentView.backgroundColor = .white

        newContentView.translatesAutoresizingMaskIntoConstraints = false
        // in this case edge insets will be 10 per each side
        NSLayoutConstraint.activate([
            newContentView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
            newContentView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10),
            newContentView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10),
            newContentView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -10),
            ])

        // and from now on, use newContentView as the holder of the subviews
    }

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

You should never change frame of the cells yourself, because it is responsibility of Table/Collection view. If take a look on Cell, you can notice that it always has a content view, and all elements should be place inside it. Should should not change constraints or frames of content view, but you can place your elements relatively to it.

Regarding your code - setting up frames is completely unrelated with constraints. (Of course you you have translatesAutoresizingMaskIntoConstraints == true frames will be converted to constraints by UIKit, but still it is not setting constraints )

I advice you to do your layout in interface builder, it will save you hours of your time, make you code cleaner and develop your skills. You can just drag&drop your lane into the cell, select it and set constraints you need.

To set constraints dynamically from you code you need to create them:

For example:

override func awakeFromNib() {
    super.awakeFromNib()
    /// Create your greeting label
    var  constraints = [NSLayoutConstraint]()
    constraints.append( greetingLabel.leftAnchor.constraintEqualToSystemSpacingAfter(contentView.leftAnchor, multiplier: 1.0))
    constraints.append( contentView.rightAnchor.constraintEqualToSystemSpacingAfter(greetingLabel.rightAnchor, multiplier: 1.0))
    constraints.append(contentView.centerYAnchor.constraint(equalTo: greetingLabel.centerYAnchor))
    contentView.addConstraints(constraints)
}

May be it will help you :

class ExampleTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44
  }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt 
      indexPath: IndexPath) -> CGFloat {
     // optionally, return an calculated estimate for the cell heights
      }

// ...

For details, See here: Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM