0

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

enter image description here

BoR
  • 83
  • 3
  • 11

3 Answers3

3

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")
    }
}
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
  • Thanks ! But Still it moving from the edge – BoR Jan 31 '18 at 19:31
  • @BoR what do you mean? do NOT set frames directly, just use a simple cell like this and you can achieve that effect.. – Milan Nosáľ Jan 31 '18 at 19:32
  • I have attached my screenshot ,still the leading and trailing are not set – BoR Jan 31 '18 at 19:38
  • @BoR attah the whole code of the cell that you are using (layout code), and also the tableView datasource and delegate code – Milan Nosáľ Jan 31 '18 at 19:39
  • @BoR depending on your needs you could also use the `layoutMarginGuide` of the contentView. See [here](https://stackoverflow.com/questions/30621245/autolayout-constraints-to-uitableviewcell-contentview-not-respected/30622685#30622685) and for a more detailed answer see [here](https://stackoverflow.com/questions/37796884/on-ios-what-are-the-differences-between-margins-edge-insets-content-insets-a/47614397#47614397) – mfaani Jan 31 '18 at 20:05
  • Thanks lot for All ! @Honey . Its working with layoutMarginGuide. Thanks Honey – BoR Jan 31 '18 at 21:05
1

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)
}
MichaelV
  • 1,231
  • 8
  • 10
  • Thanks. I want to set the constraints for the tableviewcell. I have the set frames to move the tableviewcell from their edges. – BoR Jan 31 '18 at 18:20
  • The way you addressing question is wrong. Cell is building brink of table view. Technically you can change it's frame, constraints, etc. but it doesn't meant to be done, so even it you succeed this time, any new fixes or releases of iOS can break it. Basically cell represents the shape you want to setup you constraints against. So you need to place all elements of your cell inside the view, and set up constraints to the "cell", make you "cell" transparent if you want to see background. – MichaelV Feb 01 '18 at 11:08
0

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

Jamil Hasnine Tamim
  • 4,389
  • 27
  • 43