I cannot get the right way to do the following stuff... (I'm sure I'm not that far but...)
I have a UITableView and within this table I want a particuliar cell to be displayed as a button.
At first I tried to add a button in the cell but I read that was not the right way to do it. Instead it seems better to customize the cell (and make it look like a button). The thing is, I do not really know what subview to change...
What I need:
- no arrow beeing displayed at the right of the cell (I though UITableViewCellAccessoryNone would do the trick... but it did not...).
- the cell to be blue (same blue as the one used when it's clicked)
Below is the code I use:
NSString *section = (NSString *)[sections objectAtIndex:indexPath.section];
NSNumber *row = indexPath.row;
NSString *cellValue = (NSString *)[(NSArray *)[items objectForKey:section] objectAtIndex:row];
cell.textLabel.text = cellValue;
// Make Cell look like a button (used for disconnect option)
if([[sections objectAtIndex:indexPath.section] isEqualToString:#"connection"]) {
cell.textLabel.text = #"Disconnect";
cell.textLabel.textAlignment = UITextAlignmentCenter;
for (UIView* view in cell.contentView.subviews)
{
view.backgroundColor = [UIColor clearColor];
}
cell.accessoryType= UITableViewCellAccessoryNone;
}
Thanks a lot for your help,
Luc
First of all delete the code for cell Accessory view..
and to make it looks like a button, there are several possible solutions . you can make a background image for the cell like button . if you are facing a problem of accessory view that its not hiding , make an image like a button , and set the background image property of cell .
[Cell setBackgroundImage:[UIImage imageNamed:"Yourfilename.png"]];
something like this , if this doesn't work and try adding the image in cell subview ..
[Cell addSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"imagename.png"]]];
this may help !!!
Thanks
Yasir
Related
I have been looking everywhere and have not quite found my answer.
I populating a UITableView with dynamic cells from JSON and I am trying to hide any extra cells. I turned off the separators in IB, and of course all the cell separators disappear. How do I add a line to the bottom and top of each tableviewcell so that only the cells that have information show a border? I have imported Quartz and have been playing with CALayer but can't find a solution.
I found a similar question here, but the only answer was not very helpful.
What would be a better, different way of doing this?
Here are my cellForRowAtIndexPath and my numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//set equal to the information in the array
return [_jsonDataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//create Dictionary of data in row
NSDictionary *jsoninfo = [_jsonDataArray objectAtIndex:indexPath.row];
//get required keys from dictionary and assign to vairables
NSString *title = [jsoninfo objectForKey:#"title"];
NSString *subtitle = [jsoninfo objectForKey:#"subtitle"];
NSURL *imageURL = [NSURL URLWithString:[jsoninfo objectForKey:#"series_image_URL"]];
//download the images.
NSData *imgData = [NSData dataWithContentsOfURL:imageURL];
UIImage *img = [[UIImage alloc] initWithData:imgData];
//set boarder for custom cells... I need to have a border on the top and bottom of the cells I am creating so xcode does not autofill the empty space.
//fill in text to cells
cell.textLabel.text = title;
cell.detailTextLabel.text = subtitle;
cell.imageView.image = img;
return cell;
}
I also think it's not the best idea, but if you really want to do this, here's code that will achieve what you want:
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
// Draw top border only on first cell
if (indexPath.row == 0) {
UIView *topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1)];
topLineView.backgroundColor = [UIColor grayColor];
[cell.contentView addSubview:topLineView];
}
UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.bounds.size.height, self.view.bounds.size.width, 1)];
bottomLineView.backgroundColor = [UIColor grayColor];
[cell.contentView addSubview:bottomLineView];
Put this code in the tableView:cellForRowAtIndexPath: method. The final look of your UITableView will be like this:
Take into account that this is not very good for performance, especially if you have a lot of cells. If you have a bigger amount of data, refer to this SO question for help on how to optimize the drawing.
Only try this at tableView:cellForRowAtIndexPath: method
[cell.contentView.layer setBorderColor:[UIColor grayColor].CGColor];
[cell.contentView.layer setBorderWidth:1.0f];
It sounds like a sub-optimal solution to try to "distinguish" your valid cells from empty ones with lines. A superior approach would be to clean up the data source before populating the table with it.
This is not the answer to the question, but the clean solution for the original problem.
Add an empty UIView as the footer of the UITableView. Then the empty cells will be hidden. See this answer.
Use Custom Cells. Your Datasoure (Models) should drive the information into the Custom Cells. Create a setter within the Custom Cell class that can be set at each row. as in....
Allocation your Custom Cell with reuse Id,
Pass the property that is determing if the line should show:
[cell setCustomLines:Model.property];
return the cell;
You will have far more flexibility to design the CustomCell any way you want, Images, Lines, Colors, or other ways of letting your user's see a difference among your cells.
Technically, Marco's Answer will work, and good job on a simple solution. But you will not be able to expand this very much farther this this.
I'm having some trouble getting my buttons to work below a certain y value in my table cells. I'm using a custom UITableViewCell class named "RowWhiskyContent". The default height is 44px and it's below that point my events don't seem to trigger anymore. The button displays just fine and so does everything else below that point, the event however don't seem to trigger. If i place my button half way (like at y=35) only the top part of the button triggers the event and the bottom part doesn't do a thing.
Here's the code trimmed down to the esentials:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = nil;
if(![self createView:&cell])
{
UIImage *bottle = [UIImage imageNamed:#"icon_add.png"]; //image size: 22x22
UIButton *bottleButton = [[UIButton alloc] initWithFrame:CGRectMake(60, 70, bottle.size.width, bottle.size.height)];
[bottleButton setImage:bottle forState:UIControlStateNormal];
[cell.contentView addSubview:bottleButton];
[bottleButton addTarget:self action:#selector(addToCollection:) forControlEvents:UIControlEventTouchUpInside];
cell.contentView.frame = CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, 160);
//cell.frame = cell.contentView.frame; // Tried this, didn't work.
//[tableView reloadData]; // Tried this too, didn't work either.
}
return cell;
}
// Check if cell exists and create the cell if it doesn't.
-(BOOL) createView: (UITableViewCell**) cell
{
BOOL cellExists = YES;
*cell = (RowWhiskyContent *) [myTableView dequeueReusableCellWithIdentifier:#"ContentIdentifier"];
if(*cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RowWhiskyContent" owner:self options:nil];
*cell = [topLevelObjects objectAtIndex:0];
cellExists = NO;
}
return cellExists;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return 160;
}
Since I'm setting the height of the cell and the contentView both at 160 I'm not sure what's going wrong here. Reloading the data didn't work and neither did setting the cell.frame.
Could anybody please tell me what I'm doing wrong?
Thanks in advance.
EDIT:
Added a screenshot:
Red button works fine but if I place it at the position of the green button it stops working. The contentview's background is set to purple so that explains the purple area. When clicking the cell it triggers the didSelectRowAtIndexPath so I'm guessing the the cell itself is also big enough.
This is definitely a content size issue. Your button will display outside of the frame similar to overflow in CSS, however they will not respond to events. So whatever UIView is containing your UIButton you need to make sure that it's content/frame/bounds are all set tall enough. You can also use [cell.contentView sizeToFit] to adjust it automatically to it's content.
You should definitely NOT reload data inside of the protocol methods for your UITableView.
I have the following view hierarchy in a UIView page:
2 UIButtons
1 ImageView
1 UILabel
1 UITableView - grouped style - contains only one cell (of type custom cell, created completely with code without any xib), the cell contains this view hierarchy:
ImageView
2 OHAttributedLabels [here's its gitHub page]
1 UILabel rotated vertically using CGAffineTransform method
I push the view controller of this view on a navigation controller using: pushViewController method, however, everything works fine except for the case of opening the application for the first time, when this view controller is pushed the view instantly flickers once (with some black strips on screen edges), when I navigate back to other views in the application, and then reopen this view, no flickering happens.
what is the cause of this flickering ?
thank you in advance.
p.s. the OHAttributedLabel is tested on other views in the application without any problems.
EDIT:
the following code is from view1.m (the view im talking about in the question above):
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIImage *backgroundImage = [UIImage imageNamed: #"bg1.png"];
UIImageView *backGroundImageView = [[[UIImageView alloc] initWithImage: backgroundImage] autorelease];
backGroundImageView.frame = CGRectMake(0,0,320,411);
[self.view addSubview: backGroundImageView];
[self.view sendSubviewToBack: backGroundImageView];
self.gsTableView.layer.cornerRadius = 10; // to make a the corner of the table view rounded
self.gsParagraphs = [NSArray arrayWithObjects:
NSLocalizedString(#"this is a test string this is a test string this is a test string this is a test string this is a test string this is a test string this is a test string this is a test string this is a test string" , #"test string1"),
NSLocalizedString(#"this is another test string this is another test string this is another test string this is another test string this is another test string this is another test string" , #"test string2"),
nil];
}
and the following code is for cellForRowAtIndexPath method in view1.m file:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *MyIdentifier = [NSString stringWithFormat:#"MyIdentifier %i", indexPath.row];
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
cell.imageView.image = [UIImage imageNamed: #"gs_1.jpg"];
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 5.0;
// cell.textLabel.text = [self.gsParagraphs objectAtIndex:0]; //it will become blurry
//note: the attributed label is used to easily apply justified alignment and many other options
NSMutableAttributedString* cellBody1 = [NSMutableAttributedString attributedStringWithString:[self.gsParagraphs objectAtIndex:0]];
[cellBody1 setTextAlignment:UITextAlignmentJustify lineBreakMode: UILineBreakModeWordWrap];
cell.secondTextLabel.attributedText = cellBody1;
NSMutableAttributedString* cellBody2 = [NSMutableAttributedString attributedStringWithString:[self.gsParagraphs objectAtIndex:1]];
[cellBody2 setTextAlignment:UITextAlignmentJustify lineBreakMode: UILineBreakModeWordWrap];
cell.thirdTextLabel.attributedText = cellBody2;
// cell.cellLabelTextYOffset = 10; this is necessary only for the original text label
cell.cellTitle.text = NSLocalizedString(#"Test Title", #"Test Title");
cell.cellTitleLabelWidth = 170;
return cell;
}
there is no code for viewDidAppear method
Its a little unclear why you suspect your table view controller. Is the flicker inside table's bounds?
Some suspects:
Your XIB may define one view with a black background that is covered by another view with your expected color.
a resize event can happen if the view is the wrong size by a few pixels.
a rotate event could happen when the objects are first instantiated. I have been told of a case where the view was getting a rotate from and to the same orientation which left black bars. (Not sure how that happened, but it was logged from within the delegate methods.)
If you create all the delegate methods for both the view controller and table delegates, which ones are called in what order?
I don't know if it still works, but I have used a single white button in place of a one-cell grouped table. If you never plan to add another cell, there is little need to use an entire table.
Before describing the problem, let me first point out that this is a distinct issue from this question.
The Problem
This screenshot was taken with a break set at tableView:didSelectRowAtIndexPath:, and as you can see in the simulator (far right of the image), there's a single-pixel blue line at the bottom of the selected cell. This is not the design asked for by the client, nor is it how this app used to behave: there should be no separator, even on selection.
How I Got Here
I'd initially designed this table view using custom UITableViewCell classes with corresponding nib (.xib) files and had no trouble with selections: the separator was hidden as desired. Predictably, scrolling was sluggish due to all the overhead from the view hierarchy, so I reworked the custom cells to use Loren Brichter's fast scrolling solution. Now scrolling is much faster, but I can't get rid of the separator for the life of me.
What I've tried
At the time of the screenshot above...
the table view has "Separator [None]" in IB.
the UIViewController that contains the table view has this line in viewDid Load: self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
As you can see in the screenshot, I inserted some unused lines to prove that separatorStyle is set as desired. Other testing confirms that tableView and self.tableView are equivalent pointers at that same breakpoint.
I've also tried setting tableView.separatorColor to black and to clear, all with the same result: the cells look right until a selection is made.
Manjunath: Here's the code I'm using to draw alternate backgrounds depending on whether the cell's been touched or not. You can see the difference—which is less subtle when animated—in the screenshot.
if(self.highlighted) {
textColor = [UIColor blackColor];
UIImage *bg = [UIImage imageNamed:#"image-cell-background_highlighted.png"];
[bg drawAtPoint:CGPointMake(0.0, 1.0)];
}
else {
UIImage *bg = [UIImage imageNamed:#"image-cell-background.png"];
[bg drawAtPoint:CGPointMake(0.0, 0.0)];
}
This gets called in UIImageCell.m in drawContentView:, a method inherited from Mr. Brichter's ABTableViewCell super class.
Chris,
Delving into ABTableViewCell, I see:
- (void)setFrame:(CGRect)f
{
[super setFrame:f];
CGRect b = [self bounds];
b.size.height -= 1; // leave room for the seperator line
[contentView setFrame:b];
}
Since the height of the cell is one pixel shorter than the actual cell, when the cell gets selected, that one-pixel line will bleed through in the color of the selection color. It may look like it's the separator, but it is actually the selection color.
To test, try to change that line above to be two pixels or more shorter to see what happens.
Update:
By making this change to the FastScrollingExample project's -rootViewController:
- (void)viewDidLoad
{
self.title = #"Fast Scrolling Example";
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[super viewDidLoad];
}
and commenting out:
// if(self.selected)
// {
// backgroundColor = [UIColor clearColor];
// textColor = [UIColor whiteColor];
// }
//
in -drawContentView to mimic what would happen if you didn't have the selection color showing through, then I get a screen shot like this:
alt text http://files.me.com/mahboud/7k656q
Look familiar?
How would you get around this? If you don't need to select cells, then disable cell selection. Otherwise, if you are selecting cells, then you should make the rect larger so the default selection color doesn't show through when you paint with your own selection color in -drawConentRect.
Try this:
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = NSLocalizedString(#"Cell",#"");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
I have a UITableView with reorderable rows and I'm using the standard UITableViewCell.text property to display text. When I tap Edit, move a row, tap Done, then tap the row, the built-in UILabel turns completely white (text and background) and opaque, and the blue shade to the cell doesn't show behind it. What gives? Is there something I should be doing that I'm not? I have a hacky fix, but I want the real McCoy.
Here is how to reproduce it:
Starting with the standard "Navigation-Based Application" template in the iPhone OS 2.2.1 SDK:
Open RootViewController.m
Uncomment viewDidLoad, and enable the Edit button:
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
Specify that the table has a few cells:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
In tableView:cellForRowAtIndexPath:, add a line to set the text property of a cell, and therefore to use the built-in UILabel subview:
// Set up the cell...
cell.text = #"Test";
To enable reordering, uncomment tableView:moveRowAtIndexPath:toIndexPath:. The default implementation is blank, which is fine in this case since the template doesn't include a data model.
Configure the project for the Simulator, OS 2.2.1, Build and Go. When the app comes up, tap Edit, then slide any row to a new position, tap Done, and then tap each row one at a time. Usually a tap will select a row, turn it blue, and turn its text white. But a tap on the row that you just moved does that and leaves the UILabel's background color as white. The result is a confusing white open space with blue strips on the edges. Oddly enough, after the first bogus tap, another tap appears to correct the problem.
So far I have found a hack that fixes it, but I'm not happy with it. It works by ensuring that the built-in UILabel is non-opaque and that it has no background color, immediately upon selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// hacky bugfix: when a row is reordered and then selected, the UILabel displays all crappy
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if ([[view class] isSubclassOfClass:[UILabel class]]) {
((UILabel *) view).backgroundColor = nil;
view.opaque = NO;
}
}
// regular stuff: only flash the selection, don't leave it blue forever
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
This appears to work, but I don't expect it to be a good idea forever. What is the Right Way to fix this?
This looks like a bug in UITableView's rendering, and you should file a Radar bug report on it. It's like the cells don't get refreshed properly after the move.
One way to work around this for now is to not use the built-in label, but roll your own in the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
CGRect frame = cell.contentView.bounds;
frame.origin.x = frame.origin.x + 10.0f;
UILabel *textLabel = [[UILabel alloc] initWithFrame:frame];
[textLabel setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
textLabel.tag = 1;
textLabel.textAlignment = UITextAlignmentLeft;
textLabel.backgroundColor = [UIColor clearColor];
textLabel.textColor = [UIColor blackColor];
textLabel.font = [UIFont boldSystemFontOfSize:20.0];
textLabel.numberOfLines = 1;
textLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:textLabel];
[textLabel release];
}
UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
textLabel.text = #"Test";
return cell;
}
I tried this, and it doesn't exhibit the same sort of white blank rectangle you see with the built-in label. However, adding another non-opaque view to the table cell might not be the best for overall rendering performance.
I don't know how major of a glitch this is, because Apple doesn't want you to persist a selection highlight on a table row (they've been enforcing this lately during the review process). You're supposed to place a checkmark or move on to the next level in the navigation hierarchy with a selection, at which point this white box would only be on the screen for a fraction of a second.
The trick in the solution from Brad appears to be:
textLabel.backgroundColor = [UIColor clearColor];
If you leave the background as the default you still get the problem even when you roll your own cells UITableViewCells.
The reason I left it as the default is because the documentation says it is less computationally costly to use opaque backgrounds. Ideally I wouldn't want to use [UIColor clearColor] to fix this bug.
Maybe a completely custom painted cell would somehow fix it. I haven't tried those before though.
Does anyone else have a solution for this?
Thanks for the info, I was searching how to erase the background color from a UILabel.
I used the following line:
textLabel.backgroundColor = [UIColor clearColor];
and worked perfectly!!!
thanks
Alejandra :)
Selections aren't meant to be shown for extended periods! (We got knocked on this for several of our apps)
??? That means Apple would not approve their own Calendar app on iPhone! When you go to edit the start and end times of the event, the start time is selected indefinitely, it only changes once the user taps to the next field.