Ishwarya Ishwarya -4 years ago 185
iOS Question

TableviewCell View's Wrap content in ios

I have 3 view's in UITableviewCell. the 1st view need to be match parent(like in android), and other two view's needs to be in wrap content. when i hide one of the view, the other 2 view's should occupy the cell. if i hide the 2 view's, the rest of the view occupy the cell. how we can do this using auto layout or any other concept.

enter image description here

enter image description here

The first image as three view's when i hide the 3rd view, the rest of the two view's adjust it's cell width.
i just tried.

if(color==1)
{
view2.hidden=true;
view3.hidden=true;
}
else if(color==2)
{
view3.hidden=true;
}

Answer Source

UITableView() in iOS uses reuse identifier to reuse one single cell through out the life cycle(well atleast in some cases). To achieve this kind of behaviour inside a cell you can follow several approach. The easiest one is as follows.

Using UIStackView().

In this case you can use UIStackView() to append all those UIView() objects inside the cell. UIStackView() itself inherits from UIView() but it has limited features. Firmly used to manage layout of views. Following is the ViewController screenshot from storyboard which you can follow.

Setting up views inside an UITableViewCell()

enter image description here

Remember - No constraints used upto here.

Appending all those views inside an UIStackView()

enter image description here

No constraints used till now :).

Adding constraints to UIStackView() enter image description here

Finally you can add constraints to your stackview not your subviews(BTW depends on the condition you can also change the distribution/ fill property of uistackview and yes you can also set constraints.).

Now we are done with the storyboard setup. You can make outlet of all the subviews inside your UITableviewCell() subclass and hide those as you want. After hiding rest views will be resized accordingly. For more info you can go through this following code snippet.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 if let cellOfTableView = tableView.dequeueReusableCell(withIdentifier: "cellIdentiferForOrderStatus", for: indexPath) as? OrderSuccessFailureDetailsTableViewCell{
  cellOfTableView.view3.isHidden = true
  //cellOfTableView.stackView.layoutIfNeeded() //You can call this if the layout has not properly managed.
   }
}

N.B. - You can achieve the same thing using constraints also. You just have to give constraints to all your subviews and access those using IBOutlets. When you are hiding any one of those subviews just update the constraints accordingly inside an animation block for smooth transition.

Above codes are in Swift 3.0/ Xcode 8.2.1.

Hope this helped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download