objective c- adding few subviews to a UITableViewCell - iphone

I have a UITableView that displays images, but I want some text to be displayed above and under every image.
when I add text it's being displayed in the center behind the image.
how can I programmatically control the position of subviews in my cell ?
(the number of cell changes during the program at runtime)
thanks

inside cellForRowAtIndexPath add your text as subviews (e.g. x= 10, y = 20, width = 200, height = 100) :
myText = [[UITextView alloc] initWithFrame:CGRectMake(10, 20, 200, 100)];
myText.text = #" some text here";
[self addSubview:myText];
to bring the text to the front:
[self bringSubviewToFront:myText];

I would create a custom UITableViewCell to be honest. Subclass it and add the views you want to its contentView in its initialiser, then set it up as you wish for each cell in your table view data source.

First of all you should have mentioned if you are using a custom cell or not. in case it's the built-in cell that you are using, if you don't like the way it looks you should create a custom cell. see http://www.icodeblog.com/2009/05/24/custom-uitableviewcell-using-interface-builder/
If you allready use a custom cell, my guess is that you didn't implement correctly the method
heightForRowAtIndexPath:
please check if a fix is needed...

Related

Why I cant be able to change the UITableViewCell detailTextLabel's frame (just the label's position)?

I am having a table view with default UITableViewCell of style UITableViewCellStyleValue2. I just want to move detailTextLabel few pixels to the right. I know it makes no sense to adjust its width and height :). I am trying to set detailTextLabel's frame with my x and y value. But its not affecting the its frame. I prefer to use default UITableViewCell, in this case, over a customized cell because the default UITableViewCell automatically manages the text alignment and centering of the labels..
How to change UITableViewCell detailTextLabel's frame?
Am I allowed to change its frame?
Thanks everyone..
You said you want to change the frame of detailTextLabel without using the custom cell implementation then the answer to your questions will be :-
It is not possible
No, it is not possible
For that you have to use custom cell , and add probably a textview or a label to the cell's contentView according to your needs
They have the default size with the table view cell.You can do the custom implementaion.Here is the example I am giving to you
UILabel *productNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 35, 60,20 )];
productNameLabel.textColor = [UIColor whiteColor];
productNameLabel.backgroundColor=[UIColor clearColor];
productNameLabel.text=#"Name";
[cell.contentView addSubview:productNameLabel];
[productNameLabel release];
Hope this will help you.Try to use the custom implementaion.

editable UITextArea values in UITableView

I need a basic UITableView with key and value. I modify each cell to contain a UILabel, and a UITextArea. My problem is when I click the cell, the cell gives the blue click-response, but the keyboard does not appear, and the UITextField is not showing any response for editing.
In - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath I can get the textField, and set text to it, but I want to open the keyboard for writing in the textField.
When I modify the cell, I set all UITextFields to firstResponder, without luck.
Anyone?
As far as I remember, you can use the UITableViewStyleValue1 and just set the detailTextlabel to be an UITextlabel in your CellForRow. But take care that the TextLabel has a fitting width and height. Then you dont have to select the Cell but can directly tap the UITextLabel
I looked up one of my older projects and found out I handled things a little different back then. Here is what I did:
cell = [self.aTableView dequeueReusableCellWithIdentifier:kPlaceCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier:kPlaceCell] autorelease];
}
//PlaceField = An Instance of UITextfield, which I implemented as classvar.
[self.placeField removeFromSuperview];
// setting frame and font for your textfield. If you have static text in your Textlabel you should have an higher x so maybe CGRectMake (1, 100, 218, 39)
self.placeField.frame = CGRectMake(1, 1, 318, 39);
self.placeField.font = [UIFont boldSystemFontOfSize:18.0f];
//Adding your UITextfield to the UITableViewCell contentView
[cell.contentView addSubview: self.placeField];
}
If anyone wonders: I used this tableView so that the user can create an user account and used Placeholders for (Name, Date of birth,....) so I didn't need static text. ^^
Tell me how this works for you or if you need further explanations

iPhone UITableViewCell: repositioning the textLabel

I am new to iPhone development and I am currently working on a simple RSS reader app. The problem I am having is that I need to reposition the textLabel inside the UITableViewCells. I have tried setFrame or setCenter but it doesn't do anything. Does anyone know what I need to do inside the tableView:cellForRowAtIndexPath: method to reposition the textLabel at the top of the cell (x = 0, y = 0)?
Thank you
PS: The UITableViewCell is referenced by a variable called cell. I have tried [cell setFrame:CGRectMake(0, 0, 320, 20)] with no success.
You can create a subclass for UITableViewCell and customize de textLabel frame. See that answer: Labels aligning in UITableViewCell. It's works perfectly to me.
It's my subclass
#import "UITableViewCellFixed.h"
#implementation UITableViewCellFixed
- (void) layoutSubviews {
[super layoutSubviews];
self.textLabel.frame = CGRectMake(0, 0, 320, 20);
}
#end
It's my UITableViewControllerClass:
UITableViewCellFixed *cell = (UITableViewCellFixed *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCellFixed alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
You may try indentationLevel, separatorInset and other content indentation properties of UITableViewCell object.
Seems I solved my own problem. Here's some code, in case someone runs into the same problem:
UILabel *ttitle = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)] autorelease];
ttitle.font = [UIFont boldSystemFontOfSize:13];
ttitle.textColor = [UIColor blackColor];
ttitle.textAlignment = UITextAlignmentLeft;
[ttitle setText:[[stories objectAtIndex: storyIndex] objectForKey: #"title"]];
[cell.contentView addSubview:ttitle];
The idea is to create your own label object, because the textLabel is automatically positioned and can't be moved around.
Cheers.
The reason the original poster's code doesn't work is that it appears that the frame of the textLabel is set after the UITableViewCell has been returned from your delegate method.
I noticed that I can successfully alter many properties of the textLabel, such as the text alignment, color, font, etc, but altering the frame has no effect and when I print the frame to the debugger later (like on select), the frame isn't what I set. Therefore, I conclude that the UIKit framework is altering the frame of the textLabel after it is returned from the delegate method. No doubt this is likely done because Apple engineers wanted to make sure that your text was drawn to the screen, so they measure it and alter the frame so that it will fit. They probably figured that people such as ourselves who wanted to alter the position of the text would be able to do so by subclassing, or simply adding another UILabel (or whatever) as a subview. A novice developer might have a very hard time if his or her text didn't show up in the label or was truncated because they didn't adjust the frame.
In my case, I wanted the text to be center horizontally, to be a specific color/font/size, and to be slightly higher vertically in the cell. Being too lazy to subclass this, I first tried altering the frame. When that didn't work, I tried googling the answer (found this post).
My final solution was to set the numberOfLines property to 0 and add some trailing carriage returns to my text. Now THAT is lazy.
In Swift 3 it would be
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel?.frame.origin.x = 50
}

Automatically determining the size of a UITableViewCell

I am trying to determine the size of a UITableCellView. The reason being that I am using one class for different orientations and devices.
The cell contains one subview that is supposed to fill the entire cell. Right know I'm doing this in the UITableViewCell's init method:
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
//iPad
subv = [[OrbitView alloc] initWithFrame:CGRectMake(52, 5, 660, 420) ];
}else{
//iPhone
subv = [[OrbitView alloc] initWithFrame:CGRectMake(15, 5, 290, 200) ];
}
Clearly, there must be a better way of doing this, without the magic numbers. How/Where should I set the frame of the subview in the UITableViewCell so that it fills the entire UITableViewCell?
Use the dimensions of the table view that the cell will go in. Set the autoresizingMask to flexible width to handle rotation and accessory views. This code assumes you have set the rowHeight of the table, but you could use a fraction of the screen height instead of testing the device type.
-(CGRect) cellFrameForTableView:(UITableView *)inTable {
CGRect result = [inTable frame];
result.origin = CGPointZero;
result.size.height = [inTable rowHeight];
return result;
}
Add your custom view to the cell content, not the cell, if you want auto sizing to adjust your view to leave room for cell extras like accessory views. In that case things like edit controls will adjust your custom view along with the content view.
In the past I have had trouble with flexible height views in cells, so I would go with flexible bottom margin instead.

Blurry UILabel as programmatic subview of UITableViewCell contentView

I am adding a UILabel instance as a subview of my custom UITableViewCell instance's contentView.
When I select the cell, the row is highlighted blue, except for the background of the label. The label text is sharp.
When I set the label and content view backgroundColor property to [UIColor clearColor], the label text becomes blurry.
How do I set the label background color to be clear, to allow the row highlight to come through, while still keeping the label text sharp?
One suggestion I read elsewhere was to round the label's frame values, but this did not have any effect.
CODE
Here is a snippet of my custom UITableViewCell subview's -setNeedsLayout method:
UILabel *_objectTitleLabel = [[UILabel alloc] initWithFrame:CGRectNull];
_objectTitleLabel.text = [self.awsObject cleanedKey];
_objectTitleLabel.font = [UIAppDelegate defaultObjectLabelFont];
_objectTitleLabel.highlightedTextColor = [UIColor clearColor]; //[UIAppDelegate defaultLabelShadowTint];
_objectTitleLabel.backgroundColor = [UIColor clearColor]; //[UIAppDelegate defaultWidgetBackgroundTint];
_objectTitleLabel.frame = CGRectMake(
kCellImageViewWidth + 2.0 * self.indentationWidth,
0.5 * (self.tableView.rowHeight - 1.5 * kCellLabelHeight) + kCellTitleYPositionNudge,
contentViewWidth,
kCellLabelHeight
);
_objectTitleLabel.frame = CGRectIntegral(_objectTitleLabel.frame);
_objectTitleLabel.tag = kObjectTableViewCellTitleSubviewType;
//NSLog(#"_objectTitleLabel: %#", NSStringFromCGRect(_objectTitleLabel.frame));
[self.contentView addSubview:_objectTitleLabel];
[_objectTitleLabel release], _objectTitleLabel = nil;
...
self.contentView.backgroundColor = [UIAppDelegate defaultWidgetBackgroundTint];
self.contentView.clearsContextBeforeDrawing = YES;
self.contentView.autoresizesSubviews = YES;
self.contentView.clipsToBounds = YES;
self.contentView.contentMode = UIViewContentModeRedraw;
The issue is sub-pixel rendering, which occurs when your origin (which is a float value) has a non-zero fractional component. Round to the nearest whole number and you should be fine.
In my case, having set shouldRasterize = YES on the CGLayer of the view containing the UILabel was the culprit. Removing that line made the text nice and crisp.
Ok found the problem, Make sure your parent view's coordinates are rounded as well.
I ran into this problem myself today, and read somewhere that non-integer values for the origin and size of the UILabel's frame can cause this (I know they're floats, but you know what I mean). There has got to be a more elegant solution, but this quick hack appears to have solved the problem for me:
self.valueLabel.frame = CGRectMake((int) frame.origin.x, (int) frame.origin.y, (int) frame.size.width, (int) frame.size.height);
If you find a better solution, please let me know, I'd love to replace this hack with something a bit more tasteful.
Another cause of garbled/blurry text is cell reuse. If you are de-queuing a reusable cell then it may redraw with different dimensions somewhere else and again be re-used when it gets to your cell with the garbled text.
To ensure the cells are unique be sure to allocate a new cell for the indicies where the text is garbled, and mark that UITableViewCell instance with a different reuse identifier. This is only practical of course if you're dealing with a very small number of cells and if you know exactly which cells are causing problems.
Setting shouldRasterize to YES may introduce blurriness. Set the rasterization scale and that should eliminate the blurriness. [self.layer setRasterizationScale:[[UIScreen mainScreen] scale]];
Sometimes the reason for the blurriness you have mentioned can be that labels's frame is beyond the cell frame.
Even if you see all of your text you have put inside the label on your cell, the actual label size can be bigger than the cell frame.
To check if that is the reason for the effect you see I would suggest to check/print all the data you have about labels size/location after it is instantiated and than check in the delegate method tableView:heightForRowAtIndexPath: that this fit into the cell height you are returning for the cell.
Hope it will help in your case.
Use round(); C functions are provided for a reason.
#define roundCGRectValues (frame) \
frame = CGRectMake(round(frame.origin.x),round(frame.origin.y),round(frame.size.width),round(frame.size.height));
All you need.
Does -setNeedsLayout get called even for dequeued reusable cells? If so, the cell will already have the label added to the content view, and you will draw it twice, making it blurry. You can inefficiently solve this by removing all of the content view's subviews before you add your subview:
for (UIView *subview in [[self contentView] subviews]) {
[subview removeFromSuperview];
}
A better solution would be to provide properties on your cell subclass to let you modify the content of a reused cell as-needed, rather than rebuilding its view hierarchy from scratch.