Self sizing cell just doesn't work for me - ios

I tried to follow the WWCD 2014 session 226, which introduced the way to realize self sizing cells in iOS 8 using auto layout, and it just doesn't work as it should.
HHTableViewCell.h
#import <UIKit/UIKit.h>
#interface HHTableViewCell : UITableViewCell
#property (strong, nonatomic)UILabel *title;
#end
HHTableViewCell.m
#import "HHTableViewCell.h"
#implementation HHTableViewCell
#synthesize title = _title;
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// configure control(s)
#pragma mark -- title Lable
_title = [[UILabel alloc] initWithFrame:CGRectInset(self.bounds, 15.0, 0.0)];
_title.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
_title.numberOfLines = 0;
[self.contentView addSubview:_title];
#pragma mark -- constraints
NSMutableArray *constraints = [[NSMutableArray alloc]init];
UIView *contentView = self.contentView;
[constraints addObject:[NSLayoutConstraint
constraintWithItem:_title
attribute:NSLayoutAttributeFirstBaseline
relatedBy:NSLayoutRelationEqual
toItem:contentView
attribute:NSLayoutAttributeTop
multiplier:1.8
constant:3.0]];
[constraints addObject:[NSLayoutConstraint
constraintWithItem:_title
attribute:NSLayoutAttributeFirstBaseline
relatedBy:NSLayoutRelationEqual
toItem:contentView
attribute:NSLayoutAttributeTop
multiplier:1.8
constant:3.0]];
[constraints addObject:[NSLayoutConstraint
constraintWithItem:_title
attribute:NSLayoutAttributeFirstBaseline
relatedBy:NSLayoutRelationEqual
toItem:contentView
attribute:NSLayoutAttributeTop
multiplier:1.8
constant:3.0]];
[constraints addObject:[NSLayoutConstraint
constraintWithItem:contentView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:nil
attribute:0
multiplier:1.0
constant:44.0]];
[constraints addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:#"H:|-15-[_title]-15-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(_title)]];
[self.contentView addConstraints:constraints];
}
return self;
}
#end
MMTableViewController.h
#import <UIKit/UIKit.h>
#interface MMTableViewController : UITableViewController
#end
MMTableViewController.m
#import "MMTableViewController.h"
#import "HHTableViewCell.h"
#interface MMTableViewController ()
#end
#implementation MMTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[HHTableViewCell class] forCellReuseIdentifier:#"HiCell"];
[self.tableView registerClass:[HHTableViewCell class] forCellReuseIdentifier:#"HCell"];
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
// Return the number of rows in the section.
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"HiCell";
HHTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.title.text = #"Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. ";
// Configure the cell...
NSLog(cell.title.text);
return cell;
}
#end
The cell is of fixed height and wrapping two lines of text. Looks like this:
Hello Apple. Hello Apple. Hello Apple. Hello
Aplle. Hello Apple. Hello Apple. Hello Apple...
Constraints and subviews are added programatically.
Simulator is running iOS 8.3 in Xcode 6.3.1.

For UILabel to work with constraints, looking at Apple's documentation, I think you need to set the preferredMaxLayoutWidth property:
This property affects the size of the label when layout constraints
are applied to it. During layout, if the text extends beyond the width
specified by this property, the additional text is flowed to one or
more new lines, thereby increasing the height of the label.
However, unless you want some specific cell customization, you can use the default UITableViewCell, and set numberOfLines = 0 on the provided titleLabel. It will work with UITableViewAutomaticDimension, although I've only tested it in conjunction with heightForRowAtIndexPath:.
UPDATE:
From what I've learned, you also need to set estimatedRowHeight to something in the viewDidLoad (the value doesn't even needs to be accurate/important it seems).
Here is a working example using default UITableViewCells:

Related

TableviewCells are not inserted as expected

I have a reusableTablViewCell that will be simply echoed to the tableview whenever a user gives an input in the textbook and clicks send button, my problem is that the cells are not behaving as expected few times the cells are inserted correctly and few times they won't.
Expected Behaviour: when the user clicks send button after he has finished typing some text in the text box the same value should be printed twice (like sending and receiving the same text).
//view somewhat looks like this on expected behaviour
'''''''''
' hi '
'''''''''
'''''''''
' hi '
'''''''''
Current Behaviour: Sometimes it does give me the expected behaviour, but some times both the cells are on the same side
EX:
//view when it doesn't work as expected
'''''''
' hi '
'''''''
'''''''
' hi '
'''''''
or something like
''''''''
' hi '
''''''''
''''''''
' hi '
''''''''
And sometimes when we scroll, the cells change their position(being odd Cell and Even-cell which u can see in the code) from sender to receiver and vice-versa.
My code
//FirstTableViewController.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#interface FirstTableViewController : UITableViewController
#property (strong, nonatomic) IBOutlet UITableView *messageView;
#property (nonatomic,readwrite) NSInteger counter;
#property (nonatomic,readwrite) NSMutableArray *userInput;
#property (nonatomic,readwrite) NSMutableDictionary *heightAtIndexPath;
#property (nonatomic, assign) BOOL shouldScrollToLastRow;
+ (id)sharedInstance;
#end
#interface ChatMessageCellTableViewCell : UITableViewCell
#property (nonatomic, retain) UILabel *formLabel;
#property (nonatomic, retain) UIView *bubbleBackView;
#end
//FirstTableViewController.m
#import "FirstTableViewController.h"
BOOL isReceived;
#interface ChatMessageCellTableViewCell (){
NSLayoutConstraint *leadingConstraint;
NSLayoutConstraint *trailingConstraint;
}
#end
#implementation ChatMessageCellTableViewCell
-(void) loaded{
if(isReceived){
[self.bubbleBackView setBackgroundColor:[UIColor whiteColor]];
[self.formLabel setTextColor:[UIColor blackColor]];
}
else{
[[self bubbleBackView] setBackgroundColor:[UIColor colorWithRed:(66/255) green:(137/255.0) blue:1 alpha:1.0]];
[self.formLabel setTextColor:[UIColor whiteColor]];
}
}
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
[self setBackgroundColor:[UIColor clearColor]];
self.formLabel = [UILabel new];
self.bubbleBackView = [UIView new];
//[self.bubbleBackView setBackgroundColor:[UIColor yellowColor]];
[self.bubbleBackView.layer setCornerRadius:12];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
[[self contentView] addSubview:self.bubbleBackView
];
[self loaded];
[self.bubbleBackView setTranslatesAutoresizingMaskIntoConstraints:NO];
[[self contentView] addSubview:self.formLabel];
[self.formLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
if (#available(iOS 9.0, *)) {
[self.formLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:32].active=YES;
[self.formLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-32].active=YES;
[self.formLabel.widthAnchor constraintLessThanOrEqualToConstant:250].active=YES;
[self.bubbleBackView.topAnchor constraintEqualToAnchor:_formLabel.topAnchor constant:-16].active=YES;
[self.bubbleBackView.bottomAnchor constraintEqualToAnchor:_formLabel.bottomAnchor constant:16].active=YES;
[self.bubbleBackView.trailingAnchor constraintEqualToAnchor:_formLabel.trailingAnchor constant:16].active=YES;
[self.bubbleBackView.leadingAnchor constraintEqualToAnchor:_formLabel.leadingAnchor constant:-16].active=YES;
leadingConstraint= [self.formLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:32];
trailingConstraint = [self.formLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-32];
if(isReceived){
[leadingConstraint setActive:YES];
[trailingConstraint setActive:NO];
}
else{
[leadingConstraint setActive:NO];
[trailingConstraint setActive:YES];
}
} else {
// Fallback on earlier versions
}
[self.formLabel setLineBreakMode:NSLineBreakByWordWrapping];
[self.formLabel setNumberOfLines:0];
[self.formLabel sizeToFit];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-40-[bodyLabel]-40-|" options:0
metrics:nil
views:#{ #"bodyLabel":self.formLabel}]];
}
return self;
}
#end
#interface FirstTableViewController ()
{
NSArray *messages;
FirstTableViewController *classA;
}
#end
#implementation FirstTableViewController
+(id)sharedInstance
{
static FirstTableViewController *sharedClassA = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClassA = [[self alloc] init];
});
return sharedClassA;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.heightAtIndexPath = [NSMutableDictionary new];
self.userInput = [[NSMutableArray alloc] init];
[self.tableView registerClass:[ChatMessageCellTableViewCell class] forCellReuseIdentifier:#"id"];
[[self tableView] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.tableView setBackgroundColor:[UIColor colorWithWhite:0.95 alpha:1]];
[[self navigationController] setTitle:#"Meetings"];
classA = [FirstTableViewController sharedInstance];
[classA setCounter:(classA.userInput.count)];
[classA setMessageView:(self.messageView)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
classA.counter=classA.userInput.count;
return classA.counter;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = (indexPath.row % 2 == 0 ? #"EvenCell" : #"OddCell"); //just to differentiate the sending and receiving cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
ChatMessageCellTableViewCell *messageCell = (ChatMessageCellTableViewCell*) cell;
if (messageCell == nil) {
messageCell = [[ChatMessageCellTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
if(indexPath.row % 2 == 0) // simple logic to differentiate and apply my constraints to the sending and receiving cells.
{
isReceived =TRUE;
}
else{
isReceived = FALSE;
}
[[messageCell formLabel]setText:classA.userInput[indexPath.row]];
[messageCell setSelectionStyle:UITableViewCellSelectionStyleNone];
[[self tableView] setEstimatedRowHeight:50.0];
[self.tableView setRowHeight:UITableViewAutomaticDimension];
return messageCell;
}
-(void)viewWillLayoutSubviews{
if(classA.shouldScrollToLastRow){
[classA setShouldScrollToLastRow:NO];
dispatch_async(dispatch_get_main_queue(),^{
NSIndexPath *path = [NSIndexPath indexPathForRow:(self->classA.counter)-1 inSection:0];
//Basically maintain your logic to get the indexpath
[self->classA.messageView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
});
}
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)dealloc{
NSLog(#"Dealloc!!!");
}
#end
//SecondViewController.m
//sendButtonClicked is the function from where the data is passed to the FirstViewController's tableview cell.
-(IBAction)sendButtonClicked{
NSString *input = self.ChatTextInput.text;
if([input isEqualToString:#""]){
NSLog(#"this is a nil ");
}
else{
[inputValues addObject:input];
[inputValues addObject:input];
[classA setUserInput:inputValues];
[classA setCounter:inputValues.count];
[self.ChatTextInput setText:nil];
[classA setShouldScrollToLastRow:YES];
[classA.messageView reloadData];
}
}
This is basically a chat view which I'm actually trying to achieve everything is good except this abnormal behaviour.
I hope anyone can take some time and correct me where am I wrong.
UPDATE: Any one who is looking for basic chatView in objective-C can use the code above as an reference, use the code above and correct the mentioned things in the accepted answer.
This is a typical cell reuse issue. In iOS all collections (UITableView/UICollectionView) reuses the cell and cells initWithStyle gets called only once the cell is initialised. Once tableView has enough cells with it, it will reuse the cell so initWithStyle will not get called all the time. Hence few of your cells (preferably initial ones) seems all right. As you set its constraints properly in init and for other cells which are not shown properly init was never called so your constraints were never updated. Hence shows wrong bubble.
Whats the solution?:
1. Use PrepareforReuse
every cell when it gets reused, iOS calls prepareForReuse on the cell to give developer a last chance to do all clean up
-(void) prepareForReuse {
[super prepareForReuse];
[self.formLabel setText: nil];
//set default background color or change bubble view
// do whatever clean up you wanna do here
}
2. Modify your cells method and ensure you update your constraints every time cell is shown and not just in init
lets say you add a method called:
-(void)configureView:(BOOL) isRecieved {
isReceived = isRecieved;
if(isReceived){
[leadingConstraint setActive:YES];
[trailingConstraint setActive:NO];
}
else{
[leadingConstraint setActive:NO];
[trailingConstraint setActive:YES];
}
//[self layoutIfNeeded]; might be needed here
[self loaded];
}
In your init remove code to set constraint based on isRecieved Value
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
[self setBackgroundColor:[UIColor clearColor]];
self.formLabel = [UILabel new];
self.bubbleBackView = [UIView new];
//[self.bubbleBackView setBackgroundColor:[UIColor yellowColor]];
[self.bubbleBackView.layer setCornerRadius:12];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
[[self contentView] addSubview:self.bubbleBackView
];
[self loaded];
[self.bubbleBackView setTranslatesAutoresizingMaskIntoConstraints:NO];
[[self contentView] addSubview:self.formLabel];
[self.formLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
if (#available(iOS 9.0, *)) {
[self.formLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:32].active=YES;
[self.formLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-32].active=YES;
[self.formLabel.widthAnchor constraintLessThanOrEqualToConstant:250].active=YES;
[self.bubbleBackView.topAnchor constraintEqualToAnchor:_formLabel.topAnchor constant:-16].active=YES;
[self.bubbleBackView.bottomAnchor constraintEqualToAnchor:_formLabel.bottomAnchor constant:16].active=YES;
[self.bubbleBackView.trailingAnchor constraintEqualToAnchor:_formLabel.trailingAnchor constant:16].active=YES;
[self.bubbleBackView.leadingAnchor constraintEqualToAnchor:_formLabel.leadingAnchor constant:-16].active=YES;
leadingConstraint= [self.formLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:32];
trailingConstraint = [self.formLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-32];
} else {
// Fallback on earlier versions
}
[self.formLabel setLineBreakMode:NSLineBreakByWordWrapping];
[self.formLabel setNumberOfLines:0];
[self.formLabel sizeToFit];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-40-[bodyLabel]-40-|" options:0
metrics:nil
views:#{ #"bodyLabel":self.formLabel}]];
}
return self;
}
Finally in cellForRowAtIndexPath call configureView with isReceived value
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = (indexPath.row % 2 == 0 ? #"EvenCell" : #"OddCell"); //just to differentiate the sending and receiving cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
ChatMessageCellTableViewCell *messageCell = (ChatMessageCellTableViewCell*) cell;
if (messageCell == nil) {
messageCell = [[ChatMessageCellTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
if(indexPath.row % 2 == 0) // simple logic to differentiate and apply my constraints to the sending and receiving cells.
{
isReceived =TRUE;
}
else{
isReceived = FALSE;
}
[messageCell configureView: isReceived];
[[messageCell formLabel]setText:classA.userInput[indexPath.row]];
[messageCell setSelectionStyle:UITableViewCellSelectionStyleNone];
[[self tableView] setEstimatedRowHeight:50.0];
[self.tableView setRowHeight:UITableViewAutomaticDimension];
return messageCell;
}
Hope it helps

UIsearchController inside UIViewController using Auto Layout

Has anyone been successful implementing a UIViewController that contais both a UISearchController searchBar and a UItableView while laying everything out using Auto Layout?
I'm trying to achieve something similar to what 1Password does on the iPhone: a fixed searchBar on top of a tableView (not part of its tableHeaderView). When the UISearchController that owns the searchBar gets activated, its searchBar animates to show the scope buttons and thus the tableView moves down a bit.
I have got the basics of this layout working correctly with this class:
//
// ViewController.m
// UISearchControllerIssues
//
// Created by Aloha Silver on 05/02/16.
// Copyright © 2016 ABC. All rights reserved.
//
#import "ViewController.h"
#interface ViewController () <UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupTableView];
[self setupSearchInterface];
[self setupConstraints];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars = YES;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.searchController.searchBar sizeToFit];
}
- (void)setupTableView {
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.tableView];
}
- (void)setupSearchInterface {
self.definesPresentationContext = YES;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.scopeButtonTitles = #[#"One", #"Two"];
self.searchController.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
self.searchController.searchResultsUpdater = self;
[self.view addSubview:self.searchController.searchBar];
}
- (void)setupConstraints {
NSDictionary *layoutViews = #{#"searchBar": self.searchController.searchBar, #"tableView": self.tableView, #"topLayoutGuide": self.topLayoutGuide};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[searchBar]|" options:0 metrics:nil views:layoutViews]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[tableView]|" options:0 metrics:nil views:layoutViews]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[searchBar(44)][tableView]|" options:0 metrics:nil views:layoutViews]];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSLog(#"Update should happen here");
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellID = #"CellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
}
cell.textLabel.text = [NSString stringWithFormat:#"Cell number %ld", (long)indexPath.row];
return cell;
}
#end
It is embedded in a UINavigationController instance and initially runs as expect, like the following screenshots show:
Trouble arises when the searchBar gets activated. It seems to disappear from screen, but after carefully inspecting the view, we determine that it is actually onscreen, but with a width of zero. Here's a picture showing what is presented at this time:
I'm not that experienced with Auto Layout, so I'm left thinking there must be something wrong with my constraints, although I don't mess with them when activating the UISearchController.
Is there any way of making this work?
The UISearchController moves the search bar around when it's tapped, so it doesn't always play well with your constraints.
Instead of setting your constraints directly on the search bar, add an empty placeholder view that will hold your search bar and then place the search bar in it procedurally in viewDidLoad(). Set your constraints on this placeholder instead. Just match the search bar's frame to the placeholder's bounds and leave translatesAutoresizingMaskIntoConstraints set to true.
Sorry, I'm not sure how this placeholder view will handle the size change with the scope buttons. Hopefully you can figure out how to get that part working with auto layout after the change.

Dynamic UITableViewCell Producing Undesired Results

I'm attempting to create a dynamically sized table view cell. I've read every SO question, website, article, and example Github project and can't get the layout I want without errors (in its current form, there are no errors, but the end result is as depicted in the last image).
I have a table with multiple sections. The first section has a single cell that is dynamically sized. My goal is to display this cell correctly and without errors. Here are the two different visual states the cell may have:
Here is the desired look of the cell with a Message at the bottom:
Here is desired look of the cell without the message at all:
For the code shown below, here is the result:
Here is the TableViewController:
//
// The TableViewController
//
#import <Masonry.h>
#import "CustomCell.h"
#import "MyViewController.h"
#interface MyViewController()
#property (retain, nonatomic) CheckoutHeaderView *headerView;
#property (retain, nonatomic) CustomCell *customCell;
#end
#implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] init];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.allowsSelection = NO;
[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:#"customCell"];
[self.view addSubview:self.headerView];
[self.view addSubview:self.tableView];
[self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view);
make.left.equalTo(self.view);
make.right.equalTo(self.view);
}];
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.headerView.mas_bottom);
make.left.equalTo(self.view);
make.right.equalTo(self.view);
make.bottom.equalTo(self.view);
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return self.customerCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
static dispatch_once_t onceToken;
static CustomCell *customCell;
dispatch_once(&onceToken, ^{
customCell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"customCell"];
self.customCell = customerCell;
});
self.customCell.model = self.model;
return [self calculateHeightForConfiguredSizingCell:self.customCell];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
[sizingCell setNeedsUpdateConstraints];
[sizingCell updateConstraintsIfNeeded];
sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.tableView.bounds));
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGFloat height = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1.0f;
return height;
}
#end
Here is the cell class:
#import "CustomCell.h"
#import <Masonry.h>
#import "Label.h"
#import "Order.h"
#import "Helper.h"
#import "Theme.h"
#interface CustomCell()
#property (assign, nonatomic) BOOL didSetupConstraints;
#property (retain, nonatomic) Label *dateOneLabel;
#property (retain, nonatomic) Label *dateTwoToLabel;
#property (retain, nonatomic) Label *messageLabel;
#property (retain, nonatomic) Label *dateOneValue;
#property (retain, nonatomic) Label *dateTwoToValue;
#property (retain, nonatomic) Label *messageText;
#property (retain, nonatomic) NSMutableArray *messageConstraints;
#property (retain, nonatomic) MASConstraint *pinBottomOfDateTwoLabelToBottomOfContentViewConstraint;
#end
#implementation CustomCell
- (NSMutableArray *)messageConstraints {
return _messageConstraints ? _messageConstraints : [#[] mutableCopy];
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self setup];
}
return self;
}
- (void)awakeFromNib {
[self setup];
}
- (void) setup {
self.didSetupConstraints = NO;
self.dateOneLabel = [UILabel new];
self.dateOneLabel.text = #"Date One";
self.dateTwoLabel = [UILabel new];
self.dateTwoLabel.text = #"Date Two";
self.messageLabel = [UILabel new];
self.messageLabel.text = #"Message";
self.dateOneValue = [UILabel new];
self.dateTwoToValue = [UILabel new];
// The actual message text label that spans numerous lines.
self.messageText = [UILabel new];
self.messageText.numberOfLines = 0;
self.messageText.adjustsFontSizeToWidth = NO;
[self.contentView addSubview:self.dateOneLabel];
[self.contentView addSubview:self.dateTwoToLabel];
[self.contentView addSubview:self.messageLabel];
[self.contentView addSubview:self.dateOneValue];
[self.contentView addSubview:self.dateTwoToValue];
[self.contentView addSubview:self.messageText];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
self.messageText.preferredMaxLayoutWidth = CGRectGetWidth(self.messageText.frame);
}
- (void)updateConstraints {
if (!self.didSetupConstraints) {
__weak typeof (self.contentView) contentView = self.contentView;
// Topmost label, pinned to left side of cell.
[self.dateOneLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(contentView).with.offset(14);
make.right.lessThanOrEqualTo(self.dateOneValue.mas_left).with.offset(-20);
make.top.equalTo(contentView).with.offset(14);
}];
// Second label, pinned to left side of cell and below first label.
[self.dateTwoToLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.dateOneLabel);
make.top.equalTo(self.dateOneLabel.mas_bottom).with.offset(6);
make.right.lessThanOrEqualTo(self.dateTwoToValue.mas_left).with.offset(-20);
}];
// First date value, pinned to right of cell and baseline of its label.
[self.dateOneValue mas_remakeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(contentView).with.offset(-14).priorityHigh();
make.baseline.equalTo(self.dateOneLabel);
}];
// Second date value, pinned to right of cell and baseline of its label.
[self.dateTwoToValue mas_remakeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.dateOneValue);
make.baseline.equalTo(self.dateTwoToLabel);
}];
self.didSetupConstraints = YES;
}
[super updateConstraints];
}
- (void)uninstallMessageConstraints {
[self.pinBottomOfDateTwoLabelToBottomOfContentViewConstraint uninstall];
for (MASConstraint *constraint in self.messageConstraints) {
[constraint uninstall];
}
[self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
self.pinBottomOfDateTwoLabelToBottomOfContentViewConstraint = make.bottom.equalTo(self.dateTwoToLabel).with.offset(14);
}];
}
- (void)installMessageConstraints {
__weak typeof (self.contentView) contentView = self.contentView;
[self.pinBottomOfDateTwoLabelToBottomOfContentViewConstraint uninstall];
// Below, add constraints of `self.messageConstraints` into an array so
// they can be removed later.
[self.messageConstraints addObjectsFromArray:[self.messageLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.dateOneLabel);
make.top.equalTo(self.dateTwoToLabel.mas_bottom).with.offset(6);
}]];
self.messageConstraints = [[self.messageText mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.messageLabel);
make.top.equalTo(self.messageLabel.mas_bottom).with.offset(6);
make.right.equalTo(contentView).with.offset(-14);
}] mutableCopy];
[contentView mas_makeConstraints:^(MASConstraintMaker *make) {
self.pinBottomOfDateTwoLabelToBottomOfContentViewConstraint = make.bottom.equalTo(self.messageText).with.offset(14);
}];
}
- (void)setModel:(MyModel *)model {
if (!model.message || model.message.length < 1) {
[self uninstallMessageConstraints];
self.messageText.text = #"";
[self.messageLabel removeFromSuperview];
[self.messageText removeFromSuperview];
} else {
self.messageText.text = model.message;
if (![self.contentView.subviews containsObject:self.messageLabel]) {
[self.contentView addSubview:self.messageLabel];
}
if (![self.contentView.subviews containsObject:self.messageText]) {
[self.contentView addSubview:self.messageText];
}
[self installMessageConstraints];
}
self.dateOneValue.text = model.dateOne;
self.dateTwoValue.text = model.dateTwo;
[self.contentView setNeedsDisplay];
[self.contentView setNeedsLayout];
}
#end
I've been tinkering with this for two days, and at certain points, it looked as desired, but with Autolayout Errors. I have no idea where my errors lie, so my general question is: What is wrong with my code and what needs to change to produce the correct result?
Many thanks.
I think you need to add self.messageText.lineBreakMode = NSLineBreakByWordWrapping to force it to multiple lines.

How do I create a UI TableView with multiple columns in Xcode?

I am working on a iOS 8 app with Xcode.
I need to display a table with many columns and rows of data in one view.
Example:
Name Time In Time Out ETA
Johnnys Supplies 8:30AM 9:00AM 10:15AM
Franks Company 8:45AM 9:05AM 9:45AM
Another Inc. 10:12AM 11:00AM 12:04PM
All of the data would be read in with JSON/PHP.
I need it to work like a tableview where a user can scroll vertically, and select an index. Once that index is selected, the user can click a button to run additional queries based on the data in the selected cell (etc.).
What is the easiest way to implement this? There has to be a way xcode allows you to do this natively? Am I missing something?
All coding examples welcomed!
I have found two options but both require licensing fees:
http://www.ioscomponents.com/Home/IOSDataGrid <-- $400
http://www.binpress.com/app/ios-data-grid-table-view/586 <-- $130
Anyone familiar with these components?
What's the difference between two columns and two labels next to each other? A divider?
Is this a multi column table view?
Because it's a tableview with ordinary UITableViewCell that have 3 UILabels and 2 UIViews. The views pretend to be dividers by being 1 px wide.
Code should be self explanatory.
.h
#interface MultiColumnTableViewCell : UITableViewCell
#property (strong, nonatomic) UILabel *label1;
#property (strong, nonatomic) UILabel *label2;
#property (strong, nonatomic) UILabel *label3;
#end
.m
#interface MultiColumnTableViewCell ()
#property (strong, nonatomic) UIView *divider1;
#property (strong, nonatomic) UIView *divider2;
#end
#implementation MultiColumnTableViewCell
- (UILabel *)label {
UILabel *label = [[UILabel alloc] init];
label.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:label];
return label;
}
- (UIView *)divider {
UIView *view = [[UIView alloc] init];
view.translatesAutoresizingMaskIntoConstraints = NO;
[view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:1.0/[[UIScreen mainScreen] scale]]];
view.backgroundColor = [UIColor lightGrayColor];
[self.contentView addSubview:view];
return view;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
self.separatorInset = UIEdgeInsetsZero;
self.layoutMargins = UIEdgeInsetsZero;
self.preservesSuperviewLayoutMargins = NO;
self.divider1 = [self divider];
self.divider2 = [self divider];
self.label1 = [self label];
self.label2 = [self label];
self.label3 = [self label];
NSDictionary *views = NSDictionaryOfVariableBindings(_label1, _label2, _label3, _divider1, _divider2);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-5-[_label1]-2-[_divider1]-2-[_label2(==_label1)]-2-[_divider2]-2-[_label3(==_label1)]-5-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views];
[self.contentView addConstraints:constraints];
NSArray *horizontalConstraints1 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_divider1]|" options:0 metrics:nil views:views];
[self.contentView addConstraints:horizontalConstraints1];
NSArray *horizontalConstraints2 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_divider2]|" options:0 metrics:nil views:views];
[self.contentView addConstraints:horizontalConstraints2];
return self;
}
#end
TableViewController:
#implementation MasterViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[MultiColumnTableViewCell class] forCellReuseIdentifier:#"Cell"];
self.tableView.separatorColor = [UIColor lightGrayColor];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MultiColumnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.label1.text = [NSString stringWithFormat:#"Name %ld", (long)indexPath.row];
cell.label2.text = [NSString stringWithFormat:#"Start %ld", (long)indexPath.row];
cell.label3.text = [NSString stringWithFormat:#"End %ld", (long)indexPath.row];
return cell;
}
#end
iOS table views are always a single column. On Mac OS you can create what you are after directly.
That said, you could create custom table view cells that display the content you want. In fact it would be quite easy. All you would do is to subclass UITableViewCell and define views (probably UILabels) for each of you columns, then wire them up as outlet properties in the cell. Then rig your table view to register that cell class for the cell identifier you use.
You then write your cellForRowAtIndexPath method to install your data into the different outlet properties.
You could also use a UICollectionView, but it looks to me like a table view with custom cells is a better fit for this application.
Use UICollectionView, check Apple WWDC 2012 sessions
205 Introducing Collection Views
219 Advanced Collection Views and Building Custom Layouts
from https://developer.apple.com/videos/wwdc/2012/

How to set the position of cells on UICollectionView

I have an UIViewController which contains a UICollectionView. But the UICollectionView does not fill all the UIViewController.
I find that there is space whose height equals the height of NavigationBar between the cell and the top edge of the UICollectionView. I don't know how I can set the cell position to (0,0) in the UICollectionView. (like this, the space is in the red rectangle)
I found this link How do I set the position of a UICollectionViewCell? And I subclass UICollectionViewFlowLayout (the following are my code)
MZMCollectionViewFlowLayout.h
#import <UIKit/UIKit.h>
#interface MZMCollectionViewFlowLayout : UICollectionViewFlowLayout
#end
MZMCollectionViewFlowLayout.m
#import "MZMCollectionViewFlowLayout.h"
#implementation MZMCollectionViewFlowLayout
- (CGSize)collectionViewContentSize
{
return [super collectionViewContentSize];
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return [super layoutAttributesForElementsInRect:rect];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"MZMCollectionViewFlowLayout layoutAttributesForItemAtIndexPath");
if (indexPath.section == 0 && indexPath.row == 1) // or whatever specific item you're trying to override
{
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
return layoutAttributes;
}
else
{
return [super layoutAttributesForItemAtIndexPath:indexPath];
}
}
#end
and using it like this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// hide the tool bar
[self.navigationController setToolbarHidden:YES animated:YES];
// set title
self.navigationItem.title = #"User Album";
[self.userAlbumView setCollectionViewLayout:[[MZMCollectionViewFlowLayout alloc] init]];
}
But it does not work. The log NSLog(#"MZMCollectionViewFlowLayout layoutAttributesForItemAtIndexPath"); doesn't show. And the blank is still there.
Thanks for any help!
FYI, this is answered more correctly here: UICollectionView adds top margin
The problem is the view controller is automatically adjusting scroll view insets. That can be turned off either in code or IB. In code just set:
self.automaticallyAdjustsScrollViewInsets = NO;
Answer myself question.
I printed every UICollectionViewLayoutAttribute information in layoutAttributesForElementsInRect: and found what I need is to change the frame.orgin.y
following is my code:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:[attributes count]];
for (int i=0; i< [attributes count]; i++) {
UICollectionViewLayoutAttributes *attr = (UICollectionViewLayoutAttributes *)[attributes objectAtIndex:i];
// the key code "attr.frame.origin.y - 63"
[attr setFrame:CGRectMake(attr.frame.origin.x, attr.frame.origin.y - 63, attr.bounds.size.width, attr.bounds.size.height)];
//NSLog(#"attr h=%f w=%f x=%f y=%f", attr.bounds.size.height, attr.bounds.size.width, attr.frame.origin.x, attr.frame.origin.y);
[result addObject:attr];
}
return result;
}
then it works fine.

Resources