Custom UITableViewCell won't redraw on setNeedsDisplay - iphone

I created a custom UITableViewCell class with a UIButton, a UIImage, and two UILabels. The button and the image are overlayed on top of each other, and only one is displayed at a time. The expected behavior is you touch on the button, the button disappears, and it displays the image. The UITableViewCells are set to be reused. Here's my code:
Constructor:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
unheartButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
unheartButton.backgroundColor = [UIColor clearColor];
unheartButton.frame = CGRectMake(10, 13, 20, 18);
[unheartButton addTarget:self action:#selector(onButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[unheartButton setBackgroundImage:[UIImage imageNamed:#"redheart.png"] forState:UIControlStateNormal];
imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(12, 13, 16, 16);
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int ndx = 1; ndx < 13; ndx++) {
[array addObject:[UIImage imageNamed:[NSString stringWithFormat:#"icon-loading-%d (dragged).tiff", ndx]]];
}
imageView.animationImages = array;
imageView.animationDuration = 1;
[array release];
[self.contentView addSubview:imageView];
[self.contentView addSubview:unheartButton];
return self;
}
}
- (void) setModel:(MyModel *)myModel {
model = myModel;
if (model.hideImage) {
imageView.hidden = YES;
unheartButton.hidden = NO;
else {
imageView.hidden = NO;
unheartButton.hidden = YES;
}
}
Button click:
- (IBAction) onButtonClick: (id) sender {
model.hideImage = NO;
unheartButton.hidden = YES;
imageView.hidden = NO;
[imageView startAnimating];
[self setNeedsDisplay];
[self.contentView setNeedsDisplay];
[self.unheartButton setNeedsDisplay];
[self.imageView setNeedsDisplay];
}
I'm calling setNeedsDisplay on everything, but nothing seems to happen. If I scroll off the screen and back up, the button is hidden and now the loading icon is shown, but this only happens after a scroll. I'm not sure what I need to do to get the cell to repaint.

The UITableView does some fancy caching to support scrolling and the like; I've had similar issues with refreshing a specific cell when I use custom views.
You can use reloadRowsAtIndexPaths:withRowAnimation: to make the table reload just that row. See this post for more information: Why won't my UITableViewCell deselect and update its text?

Related

how to hide custom button when editing mode is enabled?

I made a custom button using drawRect: and put it in my headerview for my tableview. I want the custom button to be hidden when editing mode is selected. i know i can do that by using the method:
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
but for some reason, my button isn't actually dissapearing when I either 1) set it to nil, 2) or use the button.hidden property. Here is my code:
TableViewController.h:
#interface ToDoTableViewController : UITableViewController <Properties2ViewControllerDelegate, UITableViewDelegate>{
addButtonView *button;
}
#property (strong, nonatomic) NSMutableArray *taskArray;
#property (strong, nonatomic) NSMutableArray *completedArray;
-(IBAction)addCell:(id)sender;
-(void)buttonPressed:(id)sender;
#end
TableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *headerView;
UIView *seperatorView;
CGRect testFrame = CGRectMake(280.0, 5.0, 30.0, 30.0);
button = [[addButtonView alloc]initWithFrame:testFrame];
NSString *sectionTitle = #"Incomplete Tasks";
NSString *section2Title = #"Completed Tasks";
UILabel *label = [[UILabel alloc]init];
label.textColor = [UIColor colorWithRed:236.0/255 green:240.0/255 blue:241.0/255 alpha:1.0f];
label.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:25];
label.backgroundColor = [UIColor clearColor];
label.frame = CGRectMake(10.0, 0.0, 320.0, 40.0);
headerView = [[UIView alloc]initWithFrame:label.frame];
[button addTarget:self action:#selector(addCell:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
CGRect sepFrame = CGRectMake(0, headerView.frame.size.height-2, 320, 1);
seperatorView = [[UIView alloc] initWithFrame:sepFrame];
seperatorView.backgroundColor = [UIColor colorWithRed:236.0/255 green:240.0/255 blue:241.0/255 alpha:1.0f];
[headerView addSubview:seperatorView];
switch (section) {
case 0:
label.text = sectionTitle;
[headerView addSubview:label];
[headerView addSubview:button];
break;
case 1:
label.text = section2Title;
[headerView addSubview:label];
// if (completedArray == nil)
// headerView.hidden = YES;
break;
}
return headerView;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if([self isEditing]){
button.hidden = YES;
}else {
button.hidden = NO;
}
}
---EDIT----
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if([self isEditing]){
button.hidden = YES;
[[self tableView] reloadData]; //shouldn't this make the button dissapear?
}else {
button.hidden = NO;
}
}
Whenever the table view is reloaded your code will recreate the entire header, including creating a new button. So you may have set the old button to hidden and then it gets destroyed and replaced by a new, visible, button.
When returning the header, either create it once and always return the same instance, then changing the hidden property should work. Or, check if the table isEditing each time the header is created and decide what to do as a result.
Let's go with the more efficient header reuse option:
Create a property to hold the header view(s) - an array.
In viewDidLoad create the header views (using your current code, but moved to a different method).
Add the header views to the property (ensure you initialise the array first)
Change viewForHeaderInSection to just return the header from the array (based on section)
In setEditing: iterate through the array and hide/show each button
(You could store the buttons in another array to make that easy)

Custom back button disappears after setting navigation bar background image

I'm using the following categories code to change
the background image of the navigation bar
#import <Foundation/Foundation.h>
#interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
#end
#import "UINavigationBar+CustomImage.h"
#implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self insertSubview:imageView atIndex:0];
[imageView release];
}
- (void) clearBackgroundImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *mySubviews = [self subviews];
for (int i = [mySubviews count] - 1; i >= 0; i--)
{
if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
[[mySubviews objectAtIndex:i] removeFromSuperview];
return;
}
}
[pool release];
}
#end
And i'm using the following code to generate the custom back button
in my view
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[btnBack addTarget:self action:#selector(goBack) forControlEvents:UIControlEventTouchUpInside];
[btnBack setImage:[UIImage imageNamed:#"back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBtnBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.leftBarButtonItem = barBtnBack;
[btnBack release];
[barBtnBack release];
But the button most of the time is hidden under the bg image
and some times it randomly appears.
Why is this happening? I'm not sure what's the problem the image is inserted at index 0
so as I understand it is supposed to be behind all the time.
Please help.
Try the following code to change background of the navigation bar in the class where you are loading the navigation bar.
#interface UINavigationBar (MyCustomNavBar)
#end
#implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect
{
UIImage *barImage = [UIImage imageNamed:#"image.png" ];
[barImage drawInRect:rect];
}
#end
Using the method Praveen S suggested you could have a global variable for the next background image name and set it in your viewDidLoad method, then in your draw rect method use the imageName stored in the variable rather than hardcoding it in the draw rect.
You should try creating the button after adding the image.

Do something to selected image in scroll view

I try to make following: Horizontal list of images, that I can select and do something with it. For example flip image around x axis. I know how to rotate image. I created scrollview and load it with images. I added event handler when I tap on image. But I don't know how to do something with tapped image. How to code method to do something with tapped image?
- (void)viewDidLoad {
[super viewDidLoad];
img1 = [UIImage imageNamed:#"imgTest.jpg"];
img2 = [UIImage imageNamed:#"imgTest2.jpg"];
arrayOfImages = [[NSMutableArray alloc] init];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
scrollView = [[UIScrollView alloc] init];
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
scrollView.directionalLockEnabled = YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor blueColor];
scrollView.autoresizesSubviews = YES;
scrollView.frame = CGRectMake(0, 0, 320, 128);
[self.view addSubview:scrollView];
UIImage *imageToAdd;
int x = 0;
int y = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
temp.frame = CGRectMake(x, y, 128, 128);
temp.userInteractionEnabled = YES;
x += 135;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapped:)];
[temp addGestureRecognizer:tap];
[scrollView addSubview:temp];
}
...
- (void)imageTapped:(UIGestureRecognizer *)sender
{
// how to get reference on selected item in scrollview???
}
A gesture recognizer has a view property that returns the view associated with the recognizer. Since you know that it'll be a UIImageView you can simply cast it and use it as in:
UIImageView *iv = (UIImageView *)[sender view];
And your image can then be queried via:
UIImage *image = [iv image];
If you need to know the index in your array, there are two ways: either simply use [arrayOfImages indexOfObject:image];, or you can assign tags (numbers) to views and use them. A tag is not used by Apple, it's only here so we developers can "mark" views in some way. For example:
NSInteger counter = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
count.tag = counter++;
...
}
Then, in your imageTapped:, you can query the index via tag:
NSInteger index = [imageView tag];

Problem with UIButton on subview of a cell

Okay, a short breif of my app before i explain the problem.
My app has two views for it's custom TableViewCell, one frontview, and one backview(which is revealed once you swipe your finger across the cell, much like the twitter-app).
Anywho, i wanted to have some buttons on the backview. I did this in the cellForRowAtIndexPath-method
The first you'll see here is how i assign labels to the cells. The secondary thing you'll see is the button. It's working fine.
UILabel *nextArtist = [UILabel alloc];
nextArtist.text = #"Rihanna";
nextArtist.tag = 4;
[cell setNextArtist:nextArtist];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(6 ,31, 110, 20);
[button setImage:[UIImage imageNamed:#"radionorge.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(touched:) forControlEvents:UIControlEventTouchUpInside];
[cell.backView addSubview:button];
But, it's in the next method the problem occours.
-(void)touched:(id)sender {
// Here i want to get the UILabels for each cell. Such as nextArtist.
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)sender;
UIView *contentView = button.superview;
UIView *viewWithTag4 = [contentView viewWithTag:4];
if ([viewWithTag1 isKindOfClass:[UILabel class]]) {
UILabel *titleLabel = (UILabel *)viewWithTag4;
NSLog(#"Label: ",titleLabel.text);
}
}
}
So, i realised that i cannot just go to the superview of the button and find my labels there, because their in another subview. I have scanned all my views, but still cannot find the label.
I am very new at this, and the subclassing of the TableView-cell is something i implemented from someone who posted their code.
But, my assumption is that there are noe UILabels in my view, because i am not adding them as views, only drawing them, with the drawTextInRect-function.
[nextArtist drawTextInRect:CGRectMake(boundsX+200 ,46, 110, 15)];
I have tried to adding them as subviews, but with no luck. Could anyone help me?
// Some more code you may need to solve the puzzle(this is where the cell-views are made)
#implementation RadioTableCellView
- (void)drawRect:(CGRect)rect {
if (!self.hidden){
[(RadioTableCell *)[self superview] drawContentView:rect];
}
else
{
[super drawRect:rect];
}
}
#end
#implementation RadioTableCellBackView
- (void)drawRect:(CGRect)rect {
if (!self.hidden){
[(RadioTableCell *)[self superview] drawBackView:rect];
}
else
{
[super drawRect:rect];
}
}
#end
#interface RadioTableCell (Private)
- (CAAnimationGroup *)bounceAnimationWithHideDuration:(CGFloat)hideDuration initialXOrigin:(CGFloat)originalX;
#end
#implementation RadioTableCell
#synthesize contentView;
#synthesize backView;
#synthesize contentViewMoving;
#synthesize selected;
#synthesize shouldSupportSwiping;
#synthesize shouldBounce;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
[self setBackgroundColor:[UIColor clearColor]];
RadioTableCellView * aView = [[RadioTableCellView alloc] initWithFrame:CGRectZero];
[aView setClipsToBounds:YES];
[aView setOpaque:YES];
[aView setBackgroundColor:[UIColor clearColor]];
[self setContentView:aView];
[aView release];
RadioTableCellBackView * anotherView = [[RadioTableCellBackView alloc] initWithFrame:CGRectZero];
[anotherView setOpaque:YES];
[anotherView setClipsToBounds:YES];
[anotherView setHidden:YES];
[anotherView setBackgroundColor:[UIColor clearColor]];
[self setBackView:anotherView];
[anotherView release];
// Backview must be added first!
// DO NOT USE sendSubviewToBack:
[self addSubview:backView];
[self addSubview:contentView];
[self setContentViewMoving:NO];
[self setSelected:NO];
[self setShouldSupportSwiping:YES];
[self setShouldBounce:YES];
[self hideBackView];
}
return self;
}
Please help me, or at least point me in a direction or two!
//////////////////////////
Updated with some new code:
This is inside my RadioCustomCell, a UIView-subclass. It's here the UILabels are drawn
#import "RadioCustomCell.h"
#implementation RadioCustomCell
#synthesize nowTitle,nowArtist,nextTitle,nextArtist,ChannelImage;
// Setting the variables
- (void)setNowTitle:(UILabel *)aLabel {
if (aLabel != nowTitle){
[nowTitle release];
nowTitle = [aLabel retain];
[self setNeedsDisplay];
}
}
- (void)setNowArtist:(UILabel *)aLabel {
if (aLabel != nowArtist){
[nowArtist release];
nowArtist = [aLabel retain];
[self setNeedsDisplay];
}
}
- (void)setNextTitle:(UILabel *)aLabel {
if (aLabel != nextTitle){
[nextTitle release];
nextTitle = [aLabel retain];
[self setNeedsDisplay];
}
}
- (void)setNextArtist:(UILabel *)aLabel {
if (aLabel != nextArtist){
[nextArtist release];
nextArtist = [aLabel retain];
[self setNeedsDisplay];
}
}
- (void)setChannelImage:(UIImage *)aImage {
if (aImage != ChannelImage){
[ChannelImage release];
ChannelImage = [aImage retain];
[self setNeedsDisplay];
}
}
- (void)drawContentView:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
//UIColor * backgroundColour = [UIColor whiteColor];
UIColor *backgroundColour = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"CellBackground.png"]];
[backgroundColour set];
CGContextFillRect(context, rect);
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
[ChannelImage drawInRect:CGRectMake(boundsX+120 ,25, 75, 35)];
nowTitle.enabled = YES;
nowTitle.textAlignment = UITextAlignmentCenter;
nowTitle.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size: 14.0];
nowTitle.textColor = [UIColor blackColor];
nowTitle.backgroundColor = [UIColor clearColor];
//[nowTitle drawTextInRect:CGRectMake(boundsX+6 ,31, 110, 20)];
// Trying to add a subview instead of drawing the text
nowTitle.frame = CGRectMake(boundsX+6 ,31, 110, 20);
[self addSubview:nowTitle];
// I have also tried adding it to super, no effect.
nowArtist.enabled = YES;
nowArtist.textAlignment = UITextAlignmentCenter;
nowArtist.font = [UIFont fontWithName:#"HelveticaNeue" size: 10.0];
nowArtist.textColor = [UIColor blackColor];
nowArtist.backgroundColor = [UIColor clearColor];
[nowArtist drawTextInRect:CGRectMake(boundsX+6 ,46, 110, 15)];
nextTitle.enabled = NO;
nextTitle.textAlignment = UITextAlignmentCenter;
nextTitle.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size: 12.0];
[nextTitle drawTextInRect:CGRectMake(boundsX+200 ,31, 110, 20)];
nextArtist.enabled = NO;
nextArtist.textAlignment = UITextAlignmentCenter;
nextArtist.font = [UIFont fontWithName:#"HelveticaNeue" size: 9.0];
[nextArtist drawTextInRect:CGRectMake(boundsX+200 ,46, 110, 15)];
}
You just forgot to init your UILabel in your very first line of code. :)
At the first look, I can be sure that if you draw the text (and the text is not the label), then there is no UILabel at all in your cell. You can ignore that way.
So, if you don't have the UILabel, how you can get the text. Because your contentView is indeed a RadioTableCellView, then it is not hard. In your class, just public a property called nextArtist. When your button is tapped, look up for the contentView (by calling some superview), cast it to RadioTableCellView then get the nextArtist out
Without writing a bunch of code, here's my best guess.
You're going to need to assign tags to aView and anotherView in your initWithStyle: method. I'm going to assume you have a couple constants: BACK_VIEW_TAG and FRONT_VIEW_TAG.
In your touched: method, walk up the view hierarchy until you find your UITableViewCell.
UIView *currentView = button.superView;
while (![currentView isKindOfClass:UITableViewCell] && currentView != nil) {
currentView = currentView.parent;
}
Get the front view and back view (or which ever you want) from the table cell's contentView using the tags.
if (currentView != nil) {
UITableViewCell *cellView = (UITableViewCell *)currentView)
UIView *cellContentView = cellView.contentView;
UIView *backView = [cellContentView viewWithTag:BACK_VIEW_TAG];
UIView *frontView = [cellContentView viewWithTag:FRONT_VIEW_TAG];
// Get other views from frontView and backView using viewWithTag:.
}
Note that you should be adding views to your UITableViewCell subclass's contentView, not to the UITableViewCell directly. See Programmatically Adding Subviews to a Cell’s Content View for details.

problem in adding second UIbutton in cameraOverlayView

problem in adding second UIbutton in cameraOverlayView ,here i am able to add the first button but not able to add second button with following code
- (void)pickAndDecodeFromSource:(UIImagePickerControllerSourceType) sourceType {
[self reset];
// Create the Image Picker
if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
UIImagePickerController* aPicker =
[[[UIImagePickerController alloc] init] autorelease];
aPicker.sourceType = sourceType;
aPicker.delegate = self;
self.picker = aPicker;
// [[NSUserDefaults standardUserDefaults] boolForKey:#"allowEditing"];
BOOL isCamera = (sourceType == UIImagePickerControllerSourceTypeCamera);
if ([picker respondsToSelector:#selector(setAllowsEditing:)]) {
// not in 3.0
[picker setAllowsEditing:!isCamera];
}
if (isCamera) {
if ([picker respondsToSelector:#selector(setShowsCameraControls:)]) {
[picker setShowsCameraControls:NO];
UIButton *cancelButton =
[UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString *cancelString =
NSLocalizedString(#"DecoderViewController cancel button title", #"");
CGFloat height = [UIFont systemFontSize];
CGSize size =
[cancelString sizeWithFont:[UIFont systemFontOfSize:height]];
[cancelButton setTitle:cancelString forState:UIControlStateNormal];
//cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"CancelButtonForButton.png"]];
//cancelButton.backgroundColor = [UIColor clearColor];
//cancelButton.backgroundColor = [UIColor greenColor];
[cancelButton setImage:[UIImage imageNamed:#"cancelForButton.png"] forState:UIControlStateNormal];
//[cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
CGRect appFrame = [[UIScreen mainScreen] bounds];
static const int kMargin = 10;
static const int kInternalXMargin = 10;
static const int kInternalYMargin = 10;
CGRect frame = CGRectMake(kMargin,
appFrame.size.height - (height + 2*kInternalYMargin + kMargin),
2*kInternalXMargin + size.width,
height + 2*kInternalYMargin);
[cancelButton setFrame:frame];
[cancelButton addTarget:self
action:#selector(cancel:)
forControlEvents:UIControlEventTouchUpInside];
picker.cameraOverlayView = cancelButton;
// The camera takes quite a while to start up. Hence the 2 second delay.
[self performSelector:#selector(takeScreenshot)
withObject:nil
afterDelay:2.0];
//cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg.png"]];
}
}
// Picker is displayed asynchronously.
[self presentModalViewController:picker animated:YES];
} else {
NSLog(#"Attempted to pick an image with illegal source type '%d'", sourceType);
}
}
The issue is that you are replacing the camera overlay with the first button - so creating the second button and using "picker.cameraOverlayView = newButton;" replaces the camera-overlay again.
The solution is to create a parent UIView, add both buttons to it, and then set the camera overlay to be the parent UIView.