UICollectionView's cellForItemAtIndexPath not recognizing individual cell frames - ios

I am having an issue adding labels to individual cells in a UICollectionView. Using the code shown bellow, the label is added only to the first cell in the collection and none of the others. However, if I change cell.contentView in the third to last line to collectionView, the labels are all added to the right locations, which means I'm dealing with at least the right frame, but I need the labels to be added to the cells themselves.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"CalendarItem"
forIndexPath:indexPath];
UILabel* dayLabel = [[UILabel alloc] initWithFrame:cell.frame];
[dayLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15]];
[dayLabel setBackgroundColor:[UIColor clearColor]];
[dayLabel setTextAlignment:NSTextAlignmentCenter];
[dayLabel setText:#"!"];
[cell.contentView addSubview:dayLabel];
[cell setBackgroundColor:[UIColor whiteColor]];
return cell;
}
I'm doing this all programmatically so here is my initialization code for the collection I'm using:
frame.origin.y = self.view.frame.origin.y + ROW_SIZE;
frame.size.height = self.view.frame.size.height/2 - 2 * ROW_SIZE;
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
CGSize size = CGSizeMake(frame.size.width/7 - 2 * CALENDAR_EDGE_SPACING,
frame.size.height/5 - 2 * CALENDAR_EDGE_SPACING);
[flow setItemSize:size];
[flow setScrollDirection:UICollectionViewScrollDirectionVertical];
calendarView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flow];
[calendarView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"CalendarItem"];

You should never be referencing the cell's frame. The collection view moves them around, removes them and generally does unexpected things with cells that you don't want to have to think about.
If you want your label to take up the entire cell you want to set the label's frame to the cell's contentView's frame. Everything should start working perfectly if you do that.
The reason using collectionView works in place of cell.contentView is because, in reality, the cell is at some arbitrary position within the collection view, say (150, 1024). So when you add a label to the content view at origin (150, 1024), it's actually way below the view that you're looking at; but when you add the label directly to the collection view it's at the same position as the cell.

Related

How to add subviews to a tableview cell dynamically

I created a custom tableview cell in IB. I add a scroll view as a subview of the cell's contentView, and create the IBOutlet in the tableview cell subclass, and make the connection. My problem is, I want to add subviews to the cell dynamically, but when I did this in code, nothing happens. The cell is rendered successfully, but the scrollView has nothing to show (no subviews on it).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// deque the cell
// create some label depending on the MODEL object
// (this is done by code, not in IB. because the label is content-based)
// we don't know how many labels in advance
[cell.scrollView addSubview: label]; // not working !!
...
return cell;
}
But if I add the subviews in IB (which means the subviews are pre-defined), it works.
Is there any ways to add the subviews to a cell dynamically ? Or maybe I put the code in the wrong place ?
Thanks for all of the responses.
This is really embarrassing. The problem is I mis-config the label property, make the label text color white, but somehow the scrollView background is also white. So I can't see the labels, but actually they are already there.
All the responses are helpful, but #Shebin's answer gave me the hint to check the color, so I think I should mark his answer as the best.
Try this
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, 130, 30)];
label1.text = #"any text";
label1.textColor = [UIColor redColor];
label1.backgroundColor = [UIColor greenColor];
[cell addSubview:label1];// first try adding to cell
if you need to add as subview of cell.scrollView
NSLog(#"scrollView %#",cell.scrollView);//it should not be nil
check scrollView content size and frame
For dynamic string this will also help you
NSString *string = #"This is the text";
CGSize stringsize = [string sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, stringsize.width+30/*you have to adjust 30 as u required*/, 30)];
label1.text = string;
label1.textColor = [UIColor redColor];
label1.backgroundColor = [UIColor greenColor];
cell.scrollView.contentSize = CGSizeMake(label1.frame.size.width+30/*you have to adjust 30 as u required*/, label1.frame.size.height);
[cell.scrollView addSubview:label1];
You need to add proper constraints on your sub views. The scrollable size of a UIScrollView is computed based on the constraints of its subviews. Please ensure that constraints on the content view of your cell is properly added.
And if you are not setting constraints on your subview like label etc. then its intrinsicContentSize is used.

Custom View with dynamic Height as UITableView Header ios xcode

In my project,i have a 1.MovieplayerView,2.a label with dynamic content,3.a tableView with variable number of rows.
I was doing this with all these views in scrollView.But i always have the issue with dynamic height of the label.it sometime overlaps the tableView.
I came to know that we can use customView as the tableView header.How this can be done with variable content Height and autolayout?I am new to iOS.Any suggestion ??
I know how to add a view as the header to a table.But when the contents in the view changes,it overlaps the contents of the tableView.
I went through
How to resize superview to fit all subviews with autolayout?,How do I set the height of tableHeaderView (UITableView) with autolayout?
Can some one give a simple example on how to do this?Or tell me if it is better to use a scrollview and add all these views as its subviews? any suggestion would be realy helpful.Thanks.
In viewDidAppear,
1. Get the height of the dynamic content, then set the height of your tableHeaderView accordingly.
2. Set the headerView again so the table view can refresh:
self.tableView.tableHeaderView = headerView
Try using following code is this what u want to achieve can u clearify me please
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 40)];
NSString *string = [NSString stringWithFormat:#"/ %#",selectedCategory];
label.font = [UIFont fontWithName:#"Helvetica" size:15.0];
label.textColor = ThemeColor;
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor colorWithRed:0.933f green:0.933f blue:0.933f alpha:1.00f]];
return view;
}
Don't forget to place this in nib of UITableView
It's hard to interpret your question regarding your use of the scroll view. If what you want is a custom view as the table view header, you could override this method in your table view class:
- (UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section

Add Margin to a custom UI Table Cell

I'm fairly new to the native app dev world and predominately a Front-End Dev/designer - I have built a IOS7 app in Xcode 5 - which contains a UITable with several custom cells. I would like to add margin of approx 8px to each of the cells (to look like the image below) - and change the colour of the link arrow which appears via a push segue - but have no idea how to do either despite a good web search / book read - theres doesnt seem to be the relevant options on the storyboard.
Can anyone advice if possible?
the code goes like this method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
for add margin of each cell (this code add margin only to top of each cell):
UIView *separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 8)];
separatorLineView.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:separatorLineView];
and for color of arrow you have to create an image and insert it with this code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 7, 11)];
[label setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"yourimage.png"]]];
cell.accessoryView = label;
You can include a margin to the cell by resizing the table itself. Instead of the standard 320 pixels width, change the width of the table to 312. That will give you an overall margin without having to meddle with the internals of the table view.
CGFloat margin = 8;
self.tableView.frame = CGRectMake(0, 0, self.view.frame.width-margin, self.view.frame.height);
In order to change the color of the arrow, you have to change what's called the accessoryView of the UITableViewCell. It can be any UIView.
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"coloredArrow.png"]];

iOS7 tableview cell.imageview extra padding?

I have a tableview which renders perfectly in iOS 6 & has done so for years. In iO7 in the same tableview either side of the cell.imageview its adding some extra padding approx 5mm either side of each image shown below thus moving my cell.textLabel.text further to the right. How would I remove this I cant seem to find the answer anywhere to this question?
In iOS7, the UITableViewCell's predefined property imageView is indented towards right by 15pt by default.
And this has nothing to do with the following UITableViewCell properties
indentationLevel
indentationWidth
shouldIndentWhileEditing
separatorInset
Therefore creating your own custom UITableViewCell is the best way to overcome it.
According to Apple, there are 2 good ways to do it:
If you want the cell to have different content components and to have these laid out in different locations, or if you want different behavioral characteristics for the cell, you have two alternatives:
Add subviews to a cell’s content view.
Create a custom subclass of UITableViewCell.
Solution:
As you don't prefer subclassing UITableViewCell, so adding custom subviews is your choice.
Simply creates your own image view and text labels, and add them through code or through storyboard. e.g.
//caution: simplied example
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//get the cell object
static NSString *CellIdentifier = #"myCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//create your own labels and image view object, specify the frame
UILabel *mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)];
[cell.contentView addSubview:mainLabel];
UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)];
[cell.contentView addSubview:secondLabel];
UIImageView *photo = [[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)];
[cell.contentView addSubview:photo];
//assign content
mainLabel.text = #"myMainTitle";
secondLabel.text = #"mySecondaryTitle";
photo.image = [UIImage imageNamed:#"myImage.png"];
return cell;
}
Note that as the predefined UITableViewCell content properties: cell.textLabel, cell.detailTextLabel and cell.imageView are untouched so they will remind nil and will not be shown.
Reference:
A Closer Look at Table View Cells
https://developer.apple.com/Library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7-SW1
Hope this help!
I probably had the same problem, the only thing that workd for me is setting the image frame:
cell.imageView.frame = CGRectMake( 0, 0, 50, 55 );
And if you are subclassing the cell, better to do:
- (void) layoutSubviews
{
[super layoutSubviews];
self.imageView.frame = CGRectMake( 0, 0, 50, 55 );
}

iOS UITableView unexpectedly adding margins

I have a UITableView, and currently it has a single cell in it. I have written a custom TableViewCell class which inherits from UITableViewCell in order to do some custom drawing. I have set the width of the table to the desired size, and am trying to set the width of the cell to the same size, so it will fill up the entire width of the table. The problem seems to be that I'm getting some margins on the left and right sides of the cell, and I don't know why.
Here's an example of the problem.
I made the TableView background black to be more clear. The TableView is the correct size. The background image is added to the cell, not the table, and it should be taking up the full width of the table.
I have tried making the TableView wider (as wide as the screen) to try to accommodate the size of the background image, but that doesn't quite do it. I would rather just figure out where these margins are coming from, and how I can get rid of them.
The TableView itself is initialized in Interface Builder. The style is set to Grouped, scrolling is disabled, and the view mode is set to Scale To Fill.
Here's the cell class' initWithStyle method
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
// Initialization code
_primaryLabel = [[UILabel alloc] init];
_primaryLabel.textAlignment = UITextAlignmentLeft;
_primaryLabel.font = [UIFont systemFontOfSize:18];
_primaryLabel.backgroundColor = [UIColor clearColor];
_detailLabel = [[UILabel alloc] init];
_detailLabel.textAlignment = UITextAlignmentLeft;
_detailLabel.font = [UIFont systemFontOfSize:12];
_detailLabel.backgroundColor = [UIColor clearColor];
_icon = [[UIImageView alloc] init];
[self.contentView addSubview:_primaryLabel];
[self.contentView addSubview:_detailLabel];
[self.contentView addSubview:_icon];
self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView* whiteDisclosureView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 13)];
[whiteDisclosureView setImage:[UIImage imageNamed:#"white_disclosure.png"]];
self.accessoryView = whiteDisclosureView;
UIImageView * background = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 305, 61)];
[background setImage:[UIImage imageNamed:#"button_silver.png"]];
[self setBackgroundView:background];
self.backgroundColor = [UIColor clearColor];
self.frame = self.contentView.frame = CGRectMake(0, 0, 305, 61);
}
return self;
}
Is your tableView using "grouped" style? With grouped style, iOS normally adds left and right margin for the table cells.
It may be possible to remedy this by adjusting the frame of the tableView to slightly outside its superview. See here for example in previous question
You shouldn't explicitly set your cell's frame (size), but declare its style. (If you don't do that already) The cells are designed to automatically take up the whole space. (Horizontally)
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
If not when allocating your cell, how do you set the cell's frame?
EDIT: Instead of using hardcoded frame sizes, use self.frame. Additionally, remove the last statement where you set the frame.
Another alternative solution I used.
#jonkroll's solution does work but it does not fulfil my need. I have a header section in the table view which I want to keep the margin left and right as is, but want to remove them on the normal cell.
The solution I did is to implement a layoutSubViews method in a custom table view cell. Within this method, set the contentView's width equal to table cell's width.
-(void)layoutSubviews {
self.contentView.frame.size.width = self.frame.size.width;
}
This may be very late, but I think some people will run into the same problem as well. Hope this solution works for you guys : )

Resources