UILabel positions not adjusting when superview changes size

Viewed 55

I am pretty new to iOS and Objective-C.

I have been trying to get a programmatically generated UITableView to work correctly. The table uses a custom UITableViewCell that is in it's own xib file, MeetingsTableViewCell.

Here is how the .xib looks:

.xib file

And the constraints for the date field:

date field constraints

Here is how it looks when run:

simulation

The date and Meeting Mode icon/label are 55 points(?) too far to the right in the simulation.

The main view controller has a width of 320 (I don't seem to be able to change that). The .xib has a width of 375 (I don't seem to be able to change that either). 55 points. Coincidence? I am guessing not.

When I used debug view hierarchy, I discovered that the Cell Wrapper View was 375 points. I added the following code (perhaps more than needed, but I was just trying everything to see if I could figure it out):

cell.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
cell.autoresizesSubviews = true;
cell.cellWrapperView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
cell.cellWrapperView.autoresizesSubviews = true;

I also made sure that I had layoutIfNeeded in the MeetingsTableCellView.m file and added code to resize cellWrapperView

-(void)layoutIfNeeded {
    [super layoutIfNeeded];
    self.cellWrapperView.frame=self.contentView.bounds;
}

That resized the views correctly to 320, but didn't move the date and meeting mode icon/label.

The debug view now looks like this:

Debug View

The TableCellView and every full-width thing inside it are 320 points wide. The date and meetings mode icon/label are (correctly) 68 points wide according to debug view. The X position is 297. I do not know how to get the date and meetings mode icon/label to be in the correct position.

As a side note, if I turn the phone to landscape, those widths are all 375 instead of 320, but shouldn't they be 568 now?

Thanks!

EDIT: The code that creates the table.

self.meetings=meetings;
self.meetingsTable=[[UITableView alloc] initWithFrame:self.tableWrapperView.bounds];
 self.meetingsTable.delegate = self;
 self.meetingsTable.dataSource = self;
 self.meetingsTable.autoresizesSubviews = true;
 self.meetingsTable.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
 self.tableWrapperView.autoresizesSubviews = true;

 UINib *cellNib=[UINib nibWithNibName:@"MeetingCellView" bundle:nil];
 [self.meetingsTable registerNib:cellNib forCellReuseIdentifier:@"MeetingsCell"];
 [self.meetingsTable reloadData];
 [self.tableWrapperView addSubview:self.meetingsTable];
1 Answers

I think you're over-complicating things a bit.

For one, you don't need the "cellWrapperView" -- it's serving no purpose that the contentView can't do.

Second, for cell layout, you shouldn't need any code in your cell class.

I did a quick test, laying out the cell (approximately) as you have:

enter image description here

and here are the results (I frequently use background colors to help see the element frames):

enter image description here enter image description here

That is accomplished with only this code...

//
//  MeetingsTableViewCell.h
//

#import <UIKit/UIKit.h>

@interface MeetingsTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *theTitleLabel;
@property (strong, nonatomic) IBOutlet UILabel *theSubTitleLabel;
@property (strong, nonatomic) IBOutlet UILabel *theDateLabel;
@property (strong, nonatomic) IBOutlet UIImageView *theImageView;
@property (strong, nonatomic) IBOutlet UILabel *theModeLabel;

@end

//
//  MeetingsTableViewCell.m
//

#import "MeetingsTableViewCell.h"

@implementation MeetingsTableViewCell

@end

//
//  TableXIBViewController.h
//

#import <UIKit/UIKit.h>

@interface TableXIBViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

//
//  TableXIBViewController.m
//
//  Created by Don Mag on 11/14/18.
//

#import "TableXIBViewController.h"
#import "MeetingsTableViewCell.h"

@interface TableXIBViewController ()

@property UITableView *meetingsTable;
@property UIView *tableWrapperView;

@end

@implementation TableXIBViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor redColor];

    // inset the table wrapper view by 20-pts so we can see its frame
    self.tableWrapperView = [[UIView alloc] initWithFrame:CGRectInset(self.view.frame, 20, 20)];
    self.tableWrapperView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [self.view addSubview:self.tableWrapperView];

    self.meetingsTable = [[UITableView alloc] initWithFrame:self.tableWrapperView.bounds];
    self.meetingsTable.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    self.meetingsTable.dataSource = self;
    self.meetingsTable.delegate = self;

    [self.tableWrapperView addSubview:self.meetingsTable];

    UINib *cellNib = [UINib nibWithNibName:@"MeetingCellView" bundle:nil];
    [self.meetingsTable registerNib:cellNib forCellReuseIdentifier:@"MeetingsCell"];

}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MeetingsTableViewCell *cell = [self.meetingsTable dequeueReusableCellWithIdentifier:@"MeetingsCell" forIndexPath:indexPath];

    cell.theTitleLabel.text = [NSString stringWithFormat:@"Meeting Title %li", indexPath.row + 1];
    cell.theSubTitleLabel.text = [NSString stringWithFormat:@"Meeting SubTitle %li", indexPath.row + 1];
    cell.theDateLabel.text = [NSString stringWithFormat:@"2018/01/0%li", indexPath.row + 1];

    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  5;
}

@end

And, to help get the cell xib laid-out correctly, here is the xib source:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14109" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
        <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" rowHeight="97" id="1hH-Nh-Uud" customClass="MeetingsTableViewCell">
            <rect key="frame" x="0.0" y="0.0" width="407" height="89"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="1hH-Nh-Uud" id="mnL-wU-yle">
                <rect key="frame" x="0.0" y="0.0" width="407" height="88.5"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="252" text="Meeting Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="6hb-sQ-pY3">
                        <rect key="frame" x="20" y="11" width="108" height="21"/>
                        <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <fontDescription key="fontDescription" type="boldSystem" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Meeting Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="gfu-sY-NvS">
                        <rect key="frame" x="20" y="57.5" width="126" height="20.5"/>
                        <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <fontDescription key="fontDescription" type="italicSystem" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="2018/01/01" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fgW-SS-i5C">
                        <rect key="frame" x="287" y="11" width="100" height="22"/>
                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstAttribute="width" constant="100" id="PgK-nv-uVx"/>
                        </constraints>
                        <fontDescription key="fontDescription" type="italicSystem" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="252" text="Meeting Mode" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="FBS-Cm-nZv">
                        <rect key="frame" x="293.5" y="62" width="87" height="16"/>
                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <fontDescription key="fontDescription" type="system" pointSize="13"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="clip" translatesAutoresizingMaskIntoConstraints="NO" id="fS2-U6-2dk">
                        <rect key="frame" x="326.5" y="37" width="21" height="21"/>
                        <constraints>
                            <constraint firstAttribute="height" constant="21" id="7U2-rp-N4R"/>
                            <constraint firstAttribute="width" constant="21" id="cKC-6E-uQn"/>
                        </constraints>
                    </imageView>
                </subviews>
                <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                <constraints>
                    <constraint firstItem="fS2-U6-2dk" firstAttribute="top" secondItem="fgW-SS-i5C" secondAttribute="bottom" constant="4" id="546-Qt-aMZ"/>
                    <constraint firstItem="gfu-sY-NvS" firstAttribute="top" relation="greaterThanOrEqual" secondItem="6hb-sQ-pY3" secondAttribute="bottom" constant="4" id="5E7-Wh-Yzw"/>
                    <constraint firstAttribute="bottomMargin" secondItem="gfu-sY-NvS" secondAttribute="bottom" id="9Bw-TS-gRW"/>
                    <constraint firstItem="FBS-Cm-nZv" firstAttribute="centerX" secondItem="fgW-SS-i5C" secondAttribute="centerX" id="G9b-b9-Ftn"/>
                    <constraint firstItem="FBS-Cm-nZv" firstAttribute="top" secondItem="fS2-U6-2dk" secondAttribute="bottom" constant="4" id="GP1-mc-D7y"/>
                    <constraint firstItem="fS2-U6-2dk" firstAttribute="centerX" secondItem="fgW-SS-i5C" secondAttribute="centerX" id="SLu-6e-2Tb"/>
                    <constraint firstAttribute="bottomMargin" secondItem="FBS-Cm-nZv" secondAttribute="bottom" id="TmX-2b-f5B"/>
                    <constraint firstAttribute="trailingMargin" secondItem="fgW-SS-i5C" secondAttribute="trailing" id="V6K-33-cCn"/>
                    <constraint firstItem="6hb-sQ-pY3" firstAttribute="top" secondItem="mnL-wU-yle" secondAttribute="topMargin" id="VkG-AA-ghx"/>
                    <constraint firstItem="6hb-sQ-pY3" firstAttribute="leading" secondItem="mnL-wU-yle" secondAttribute="leadingMargin" id="osP-fz-3fL"/>
                    <constraint firstItem="fgW-SS-i5C" firstAttribute="top" secondItem="mnL-wU-yle" secondAttribute="topMargin" id="paN-Pg-Bzz"/>
                    <constraint firstItem="gfu-sY-NvS" firstAttribute="leading" secondItem="mnL-wU-yle" secondAttribute="leadingMargin" id="x4d-ek-CE0"/>
                </constraints>
            </tableViewCellContentView>
            <connections>
                <outlet property="theDateLabel" destination="fgW-SS-i5C" id="33H-KL-zyk"/>
                <outlet property="theImageView" destination="fS2-U6-2dk" id="vgC-kz-BOU"/>
                <outlet property="theModeLabel" destination="FBS-Cm-nZv" id="BFI-rF-5c3"/>
                <outlet property="theSubTitleLabel" destination="gfu-sY-NvS" id="0bF-xI-U6a"/>
                <outlet property="theTitleLabel" destination="6hb-sQ-pY3" id="bRS-vo-UlK"/>
            </connections>
            <point key="canvasLocation" x="-30.5" y="19.5"/>
        </tableViewCell>
    </objects>
    <resources>
        <image name="clip" width="41" height="42"/>
    </resources>
</document>
Related