selection of cell is repeating while loading in tableview in objective c - objective-c

Tick mark button selection of uitableview cell is repeating when scroll the tableview. and the tableview is already loaded with an array of item. but i need to do multi selection of cells in tableview
-(void)checkButtonClicked:(UIButton *)sender{
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:touchPoint];
sender.tag = indexPath.row;
selectedIndexForPassing = sender.tag;
if([_selectionArray count ] == 0){
_uploadSheetBtn.enabled = NO;
if (sender.selected){
sender.selected = false;
}
else{
TCSTimeSheet * sc = self.timesheetList[selectedIndexForPassing];
_canEdit = sc.canEdit;
if([_canEdit isEqual: #"1"]){
sender.selected = true;
_uploadSheetBtn.enabled = YES;
TCSTimeSheet * sc = self.timesheetList[selectedIndexForPassing];
NSDictionary * detailsDictionary= [NSDictionary dictionaryWithObjectsAndKeys:sc.timesheetDetailId,#"timesheetDetailId",sc.scheduleEmployeeDetailId, #"scheduleDetailId",sc.lastUpdatedTime,#"lastUpdatedTime",sc.timesheetStatus,#"timesheetStatus",sc.shiftDate , #"shiftDate",sc.employeeId ,#"employeeId",nil];
[_storingArray addObject:detailsDictionary];
[_selectionArray addObject:sc.clientId];
}
}
}
here is my cell for at indexpath code
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * reuseIdentifier = #"timeSheetCell" ;
TimeSheetCell * dataCell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
TCSTimeSheet * currentTimeSheet = self.timesheetList[indexPath.row] ;
_statusIndicator = currentTimeSheet.timesheetStatus;
_timesheetDetailId = currentTimeSheet.timesheetDetailId;
_timesheetDocId = currentTimeSheet.timesheetDocId;
_documentType = currentTimeSheet.documentType;
if(![currentTimeSheet.notes isEqual:#""]){
_notes = currentTimeSheet.notes;
}
if (dataCell == nil)
{
dataCell = [[TimeSheetCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
}
dataCell.clientNameLbl.text = currentTimeSheet.clientName;
dataCell.dayLbl.text = currentTimeSheet.shiftDay;
dataCell.dateLbl.text = currentTimeSheet.shiftDate;
dataCell.shiftTime.text = currentTimeSheet.shiftTime;
dataCell.shiftType.text = currentTimeSheet.shiftType;
[dataCell.checkBtn addTarget:self action:#selector(checkButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
if ([_statusIndicator isEqual: #"D"]) {
if([currentTimeSheet.canEdit isEqual:#"1"]) {
[dataCell.remarkBtn setImage:[UIImage imageNamed:#"selectedMessage_btn"] forState:UIControlStateNormal];
dataCell.containerView.backgroundColor = [UIColor colorWithDisplayP3Red:255.0 green:191.0 blue:0 alpha:0.5];
if(![currentTimeSheet.notes isEqual:#""]){
[dataCell.remarkBtn addTarget:self action:#selector(presentMessagePopUp:) forControlEvents:UIControlEventTouchUpInside];
}
}
}
else if ([_statusIndicator isEqual: #"U"]){
if([currentTimeSheet.canDelete isEqual:#"1"]){
[dataCell.remarkBtn setImage:[UIImage imageNamed:#"selectedDelete_btn"] forState:UIControlStateNormal];
[dataCell.remarkBtn addTarget:self action:#selector(deleteDocument:) forControlEvents:UIControlEventTouchUpInside];
}
}
else{
[dataCell.remarkBtn setImage:[UIImage imageNamed:#"unselectedDelete_btn"] forState:UIControlStateNormal];
dataCell.containerView.backgroundColor = [UIColor colorWithDisplayP3Red:255 green:255 blue:255 alpha:1];
[dataCell.checkBtn setImage:[UIImage imageNamed:#"timesheetUnselectedTick"] forState:UIControlStateNormal];
}
if([_timesheetDocId isEqual: #""] && [_timesheetDetailId isEqual:#""]) {
[dataCell.previewBtn setImage:[UIImage imageNamed:#"unselectedView_btn"] forState:UIControlStateNormal];
}
else {
[dataCell.previewBtn setImage:[UIImage imageNamed:#"selectedView_btn"] forState:UIControlStateNormal];
if([_documentType isEqual:#"image"]){
[dataCell.previewBtn addTarget:self action:#selector(buttonClickedToShowImage:) forControlEvents:UIControlEventTouchUpInside];
}
else {
[dataCell.previewBtn addTarget:self action:#selector(buttonClickedToShowDocuments:) forControlEvents:UIControlEventTouchUpInside];
}
}
return dataCell ;
}
**button action of the tick mark**
-(void)checkButtonClicked:(UIButton *)sender{
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:touchPoint];
sender.tag = indexPath.row;
selectedIndexForPassing = sender.tag;
if([_selectionArray count ] == 0){
_uploadSheetBtn.enabled = NO;
if (sender.selected){
sender.selected = false;
}
else{
TCSTimeSheet * sc = self.timesheetList[selectedIndexForPassing];
_canEdit = sc.canEdit;
if([_canEdit isEqual: #"1"]){
sender.selected = true;
_uploadSheetBtn.enabled = YES;
TCSTimeSheet * sc = self.timesheetList[selectedIndexForPassing];
NSDictionary * detailsDictionary= [NSDictionary dictionaryWithObjectsAndKeys:sc.timesheetDetailId,#"timesheetDetailId",sc.scheduleEmployeeDetailId, #"scheduleDetailId",sc.lastUpdatedTime,#"lastUpdatedTime",sc.timesheetStatus,#"timesheetStatus",sc.shiftDate , #"shiftDate",sc.employeeId ,#"employeeId",nil];
[_storingArray addObject:detailsDictionary];
[_selectionArray addObject:sc.clientId];
}
}
}
else{
TCSTimeSheet * sc = self.timesheetList[selectedIndexForPassing];
if (sender.selected){
NSDictionary * detailsDictionary= [NSDictionary dictionaryWithObjectsAndKeys:sc.timesheetDetailId,#"timesheetDetailId",sc.scheduleEmployeeDetailId, #"scheduleDetailId",sc.lastUpdatedTime,#"lastUpdatedTime",sc.timesheetStatus,#"timesheetStatus",sc.shiftDate,#"shiftDate",sc.employeeId,#"employeeId",nil];
sender.selected = false;
[_storingArray removeObject:detailsDictionary];
//[_selectionArray removeAllObjects];
if([_storingArray count] == 0){
_uploadSheetBtn.enabled = NO;
[_selectionArray removeAllObjects];
}
}
else{
if([_selectionArray firstObject] == sc.clientId){
_uploadSheetBtn.enabled = YES;
sender.selected = true;
NSDictionary * detailsDictionary= [NSDictionary dictionaryWithObjectsAndKeys:sc.timesheetDetailId,#"timesheetDetailId",sc.scheduleEmployeeDetailId, #"scheduleDetailId",sc.lastUpdatedTime,#"lastUpdatedTime",sc.timesheetStatus,#"timesheetStatus",sc.shiftDate , #"shiftDate",sc.employeeId ,#"employeeId",nil];
[_storingArray addObject:detailsDictionary];
}
else{
sender.selected = false;
UIAlertView *alertCantDisply=[[UIAlertView alloc]initWithTitle:#"Can't Select" message:#"Can choose same client only" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertCantDisply show];
}
}
}
}

The cell will reuse, but the model will not, and the state of the view should be recorded in the model

Related

TableView reloadData does not remove images

I have tableView with multiple types of dynamic prototype cells. When I call reloadData in viewDidLoad most of the data gets reloaded but the images remain and overlap with the new content. Is there another command that I'm missing?
Here's the code snippet (tried to edit it down for simplicity):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PFObject *question = [self.friendsPosts objectAtIndex:indexPath.row];
...
else if ([[question objectForKey:#"questionType"] isEqualToString:#"PhotoChoice"]) {
static NSString *CellIdentifier = #"PhotoChoiceCell";
PhotoChoiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFUser *asker = [question objectForKey:#"asker"];
[asker fetch];
cell.question = question;
cell.usernameLabel.text = asker.username;
cell.questionLabel.text = [question objectForKey:#"questionText"];
cell.delegate = self;
[cell setCellIndexPath:indexPath];
[cell.questionLabel adjustFontSizeToFit];
cell.answered = false;
NSDate *postedTime = [question createdAt];
NSString *postedAgo = [postedTime dateTimeAgo];
cell.timeLabel.text = postedAgo;
[cell.likeButton setTitle:[NSString stringWithFormat:#"Likes (%#)", [question objectForKey:#"likes"]] forState:UIControlStateNormal];
cell.commentButton.text = [NSString stringWithFormat:#"Comments (%lu)", (unsigned long)[[question objectForKey:#"comments" ] count]];
PFRelation *allAnswerers = [question objectForKey:#"answerersRelation"];
PFQuery *answerersQuery = [allAnswerers query];
[answerersQuery whereKey:#"objectId" equalTo:[[PFUser currentUser] objectId]];
[answerersQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
if (error) {
NSLog(#"Error %# %#", error, [error userInfo]);
}
else {
if (number == 0) {
if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"2" ]) {
[cell.photoButtonA1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonA2 setImage:allImages[1] forState:UIControlStateNormal];
cell.photoButtonA1.hidden = NO;
cell.photoButtonA2.hidden = NO;
}
else if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"3"] ) {
[cell.photoButtonB1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonB2 setImage:allImages[1] forState:UIControlStateNormal];
[cell.photoButtonB3 setImage:allImages[2] forState:UIControlStateNormal];
cell.photoButtonB1.hidden = NO;
cell.photoButtonB2.hidden = NO;
cell.photoButtonB3.hidden = NO;
}
else if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"4"] ) {
[cell.photoButtonC1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonC2 setImage:allImages[1] forState:UIControlStateNormal];
[cell.photoButtonC3 setImage:allImages[2] forState:UIControlStateNormal];
[cell.photoButtonC4 setImage:allImages[3] forState:UIControlStateNormal];
cell.photoButtonC1.hidden = NO;
cell.photoButtonC2.hidden = NO;
cell.photoButtonC3.hidden = NO;
cell.photoButtonC4.hidden = NO;
}
}
So, I should have made it clear that the images were set as UIButtons.
OK, here is my guess:
You seem to have three types of cell: one with 2 images, one with 3, and one with 4; but they are all of the same class and use the same cell identifier.
So when you recycle (dequeue) your table cells, you might be reusing a cell that was previously assigned 4 images, but this time using it as a 2-image cell. Thus, you update only 2 images of the previous 4, and the other two remain unchanged. You should set the remaining images to nil when you set less than 4 images to a cell (2 or 3).
Although without further details on the pattern of occurrence of your bug, it is hard to tell.
Try this modification to your code:
// (previous code omitted)
if (number == 0) {
// Reset all cell images, regardless of type
[cell.photoButtonA1 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonA2 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonB1 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonB2 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonB3 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonC1 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonC2 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonC3 setImage:nil forState:UIControlStateNormal];
[cell.photoButtonC4 setImage:nil forState:UIControlStateNormal];
//
if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"2" ]) {
[cell.photoButtonA1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonA2 setImage:allImages[1] forState:UIControlStateNormal];
cell.photoButtonA1.hidden = NO;
cell.photoButtonA2.hidden = NO;
}
else if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"3"] ) {
[cell.photoButtonB1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonB2 setImage:allImages[1] forState:UIControlStateNormal];
[cell.photoButtonB3 setImage:allImages[2] forState:UIControlStateNormal];
cell.photoButtonB1.hidden = NO;
cell.photoButtonB2.hidden = NO;
cell.photoButtonB3.hidden = NO;
}
else if ( [[question objectForKey:#"numPhotos"] isEqualToString:#"4"] ) {
[cell.photoButtonC1 setImage:allImages[0] forState:UIControlStateNormal];
[cell.photoButtonC2 setImage:allImages[1] forState:UIControlStateNormal];
[cell.photoButtonC3 setImage:allImages[2] forState:UIControlStateNormal];
[cell.photoButtonC4 setImage:allImages[3] forState:UIControlStateNormal];
cell.photoButtonC1.hidden = NO;
cell.photoButtonC2.hidden = NO;
cell.photoButtonC3.hidden = NO;
cell.photoButtonC4.hidden = NO;
}
}
// (following code omitted)

Preload UICollectionViewCells

I've got a Uicollectionview with about 800 cells in it which is very slow when scrollign or zooming in or out.
The Method updateVisibleCellsNow takes about 9000 ms and slows down the App.
I still set
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
But it didn't work at all.
So i've tried to cache all the cells at viewDidLoad, cache them in an NSCache and access them from the cahce, but it seams like I am forced to user a reuseIdentifiert and can't access created Cells from the cache.
Is there any solution for this problem?
greetings,
Alex
MY Custom CollectionViewCell:
My .h File
#interface AECalendarCell : UICollectionViewCell
{
AEProjectDayItem *item;
NSIndexPath *thePath;
UILabel *lbl;
}
#property(nonatomic, strong) UILabel *lbl;
#property(nonatomic, strong) NSIndexPath *thePath;
#property(nonatomic, strong) AEProjectDayItem *item;
#property (nonatomic) CGFloat scale;
#property bool isAM;
-(void)redrawCellWithString:(NSString*)String;
#end
My .m File
#implementation AECalendarCell
#synthesize lbl, item, thePath;
-(id)initWithFrame:(CGRect)frame
{
if (self == [super initWithFrame:frame]) {
lbl = [[UILabel alloc]init];
}
return self;
}
-(void)redrawCellWithString:(NSString*)String
{
[lbl removeFromSuperview];
lbl.frame = self.contentView.bounds;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
if(self.scale >= 0.9)
lbl.font = [UIFont fontWithName:#"Arial" size:14];
else if(self.scale >= 0.8)
lbl.font = [UIFont fontWithName:#"Arial" size:12];
else if(self.scale >= 0.7)
lbl.font = [UIFont fontWithName:#"Arial" size:10];
else if(self.scale >= 0.6)
lbl.font = [UIFont fontWithName:#"Arial" size:8];
else if(self.scale >= 0.5)
lbl.font = [UIFont fontWithName:#"Arial" size:6];
lbl.backgroundColor = [UIColor clearColor];
lbl.textAlignment = NSTextAlignmentCenter;
if ([String isEqualToString:#""])
lbl.text = #" ";
else
lbl.text = String;
lbl.textColor = [UIColor blackColor];
if(thePath.section == 1 && thePath.item == 0)
{
CALayer *edgeBorder = [CALayer layer];
[edgeBorder setBackgroundColor:[[UIColor blackColor] CGColor]];
[edgeBorder setFrame:CGRectMake(self.bounds.size.width-2, self.bounds.size.height-2, 2, 2)];
[lbl.layer addSublayer:edgeBorder];
}
if(thePath.section == 1 && thePath.item>0)
{
CALayer *bottomBorder = [CALayer layer];
[bottomBorder setBackgroundColor:[[UIColor blackColor] CGColor]];
[bottomBorder setFrame:CGRectMake(0, self.bounds.size.height-2, self.bounds.size.width, 2)];
[lbl.layer addSublayer:bottomBorder];
}
if(thePath.section > 1 && thePath.item == 0)
{
CALayer *rightBorder = [CALayer layer];
[rightBorder setBackgroundColor:[[UIColor blackColor] CGColor]];
[rightBorder setFrame:CGRectMake(self.contentView.bounds.size.width-2, 0, 2, self.contentView.bounds.size.width)];
[lbl.layer addSublayer:rightBorder];
}
if(thePath.section > 1 && thePath.row > 1 && thePath.row %2 == 0)
{
CALayer *endofDayLayer = [CALayer layer];
[endofDayLayer setFrame:CGRectMake(self.frame.size.width-2, 0, 2, self.frame.size.width)];
if(thePath.section % 2 == 0)
[endofDayLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
else
[endofDayLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[self.lbl.layer addSublayer:endofDayLayer];
}
[self.contentView addSubview:lbl];
}
-(void)prepareForReuse
{
[super prepareForReuse];
lbl.layer.sublayers = NULL;
[lbl removeFromSuperview];
}
Adding the Cell:
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
AECalendarCell *cell = [CV_plantabel dequeueReusableCellWithReuseIdentifier:#"identifier" forIndexPath:indexPath];
if(cell == nil)
{
cell = [[AECalendarCell alloc]init];
}
cell.thePath = indexPath;
cell.scale = scale;
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setDateFormat:#"dd.MM.yyyy"];
NSDateFormatter *headerDateFormatter=[[NSDateFormatter alloc] init];
[headerDateFormatter setDateFormat:#"dd.MM"];
NSDate *today = [DateFormatter dateFromString:[DateFormatter stringFromDate:startDate]];
NSDate *headerDay;
if(indexPath.section == 0)
headerDay = [today dateByAddingTimeInterval:60*60*24*(indexPath.row-1)];
else
headerDay = [today dateByAddingTimeInterval:60*60*12*(indexPath.row-1)];
if(indexPath.section==0)
{
cell.backgroundColor = [UIColor grayColor];
if(indexPath.row>0)
[cell redrawCellWithString:[headerDateFormatter stringFromDate:headerDay]];
}
else if(indexPath.section == 1)
{
cell.backgroundColor = [UIColor grayColor];
if(indexPath.row == 0)
[cell redrawCellWithString:#"Name"];
else
{
if(indexPath.row % 2 == 1)
{
[cell redrawCellWithString:#"AM"];
}
else
{
[cell redrawCellWithString:#"PM"];
}
}
}
else
{
[cell redrawCellWithString:#""];
if(indexPath.row % 2 == 1)
{
cell.item = [[AEProjectDayItem alloc]initWithDate:headerDay andUser:[[[users objectAtIndex:indexPath.section-2]valueForKey:#"userID"]intValue] andisAM:YES];
}
else
{
cell.item = [[AEProjectDayItem alloc]initWithDate:headerDay andUser:[[[users objectAtIndex:indexPath.section-2]valueForKey:#"userID"]intValue] andisAM:NO];
}
//set Colors
if(indexPath.section % 2 == 0)
{
[cell setBackgroundColor:[UIColor grayColor]];
}
else
{
[cell setBackgroundColor:[UIColor darkGrayColor]];
}
//set Data
if(indexPath.item == 0)
{
if(self.currentScale >= 0.6)
[cell redrawCellWithString:[[users objectAtIndex:indexPath.section-2]valueForKey:#"name"]];
else
[cell redrawCellWithString:[[users objectAtIndex:indexPath.section-2]valueForKey:#"nachname"]];
}
//adjust row height
for(NSArray *item in projectDayItems)
{
if(indexPath.item>0)
{
if([[item valueForKey:#"datum"]isEqualToString:[DateFormatter stringFromDate:headerDay]] &&
[[item valueForKey:#"AM"]boolValue] == cell.item.isAM &&
[[item valueForKey:#"userID"]integerValue] == cell.item.theUserID &&
cell.item != NULL)
{
cell.item.projectDayId = [[item valueForKey:#"projectDayID"]integerValue];
cell.item.bereich = [item valueForKey:#"bereich"];
cell.item.project = [[AEProject alloc]initwithID:[[item valueForKey:#"projectID"]integerValue] andName:[item valueForKey:#"projectname"]];
cell.item.theClass = [item valueForKey:#"class"];
cell.item.sequenceID = [[item valueForKey:#"sequence"]integerValue];
[cell redrawCellWithString:cell.item.project.projectName];
}
else
{
[cell redrawCellWithString:cell.item.project.projectName];
}
}
}
}
//set the Accessibility Label
if(cell.item != NULL && indexPath.section > 1 && indexPath.item>0)
{
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setDateFormat:#"EEEE, d. MMMM"];
NSString *accString;
if(cell.item.project != nil)
{
if(cell.item.isAM)
accString = [NSString stringWithFormat:#"%# Vormittag, %# für %#", [DateFormatter stringFromDate:cell.item.theDate], cell.item.project.projectName, [[users objectAtIndex:indexPath.section-2]valueForKey:#"name"]];
else
accString = [NSString stringWithFormat:#"%# Nachmittag, %# für %#", [DateFormatter stringFromDate:cell.item.theDate], cell.item.project.projectName, [[users objectAtIndex:indexPath.section-2]valueForKey:#"name"]];
cell.lbl.accessibilityLabel = accString;
}
else
{
if(cell.item.isAM)
accString = [NSString stringWithFormat:#"%# Vormittag für %#", [DateFormatter stringFromDate:cell.item.theDate], [[users objectAtIndex:indexPath.section-2]valueForKey:#"name"]];
else
accString = [NSString stringWithFormat:#"%# Nachmittag für %#", [DateFormatter stringFromDate:cell.item.theDate], [[users objectAtIndex:indexPath.section-2]valueForKey:#"name"]];
cell.lbl.accessibilityLabel = accString;
}
}
//set Layout
if(indexPath.row > 0 && indexPath.section > 1)
[self setLayoutforCell:cell];
[self setCell:cell forIndexPath:indexPath];
return cell;
}
You create your cells without identifier, you should add this line when your view is being loaded.
[self.collectionView registerClass:[AECalendarCell class] forCellWithReuseIdentifier:#"identifier"];

how to show data to only visible tableview cells in ios

Hi guys i have a custom tableview cell with a scrollview in it.the problem is all the data is getting loaded in tableview cells at once.what i want is to load the data only for the visible cells in tableView.i used [indexPath forvisiblerows]; it was in vain..cud u guys help me out below is the code.
-(IPadTableViewCell *)getNewCell
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"IpadTableViewCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if ([currentObject isKindOfClass:[IPadTableViewCell class]])
{
cell= (IPadTableViewCell *)currentObject;
return cell;
}
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// static NSString *CellIdentifier = #"IpadTableViewCell";
//cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
id1=[NSString stringWithFormat:#"%i",indexPath.row];
cell=[dicAlbumCells objectForKey:id1];
if (cell == nil) {
cell=[self getNewCell];
}
cell.tag=indexPath.row;
return cell;
}
-(void)loadImagesForOnscreenRows
{
NSArray *visiblePaths = [tblGallery indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths) {
if (imageArray > 0) {
[self imageButtonClicked:nil];
}
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
-(void)imageButtonClicked:(id)sender
{
CGFloat prevButtonXPosition = 18, pageButtonXPosition, pageButtonWidth = 144, pageButtonHeight = 143;
for (NSInteger i =0; i<9; i++) {
pageButtonXPosition = prevButtonXPosition ;
prevButtonXPosition = pageButtonXPosition+pageButtonWidth+20;
UIButton *pageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pageButton setContentMode:UIViewContentModeScaleAspectFit];
pageButton.layer.borderColor=[[UIColor whiteColor]CGColor];
pageButton.layer.borderWidth = 3;
pageButton.layer.cornerRadius = 0;
[pageButton addTarget:self action:#selector(onClickImage:) forControlEvents:UIControlEventTouchUpInside];
[pageButton setFrame:CGRectMake(pageButtonXPosition,0, pageButtonWidth, pageButtonHeight)];
[pageButton setBackgroundImage:[UIImage imageNamed:[imageArray objectAtIndex:i]] forState:UIControlStateNormal];
[pageButton setTag:i];
[cell.scrollView addSubview:pageButton];
}
UIButton *add=[UIButton buttonWithType:UIButtonTypeCustom];
add.layer.borderColor=[[UIColor whiteColor]CGColor];
add.layer.borderWidth = 3;
add.layer.cornerRadius = 0;
[add addTarget:self action:#selector(onClickAdd:) forControlEvents:UIControlEventTouchUpInside];
[add setFrame:CGRectMake(prevButtonXPosition, 0, 144, 143)];
[add setBackgroundImage:[UIImage imageNamed:#"grey.png"] forState:UIControlStateNormal];
[add setTag:0];
[cell.scrollView addSubview:add];
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(prevButtonXPosition+35,30, 76,76)];
[iv setImage:[UIImage imageNamed:#"last.png"]];
[cell.scrollView addSubview:iv];
[cell.scrollView setContentSize:CGSizeMake(prevButtonXPosition +165, 40)];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell.contentView addSubview:cell.scrollView];
}

Remove top shadow in my grouped UITableView?

I am a little OCD and this is driving me insane. I have been messing around with these settings for a long time.
I have a UITableView grouped that I have a shadow on the top. When you tap the top cell, it removes. What gives?
I've been stressing over this for the past hour or so. Is there a simple solution for this? Or am I just going insane?
Thanks,
Coulton
EDIT:
viewDidLoad:
formTableView.backgroundColor = [UIColor clearColor];
formTableView.layer.borderColor = [UIColor clearColor].CGColor;
formTableView.separatorColor = [UIColor colorWithRed:(194.0 / 255.0) green:(194.0 / 255.0) blue:(194.0 / 255.0) alpha: 1];
Here is how I display my cells. WARNING: It's a lot of code. There's a bunch of stuff in there you will have to sort through, so sort through it at your own risk! :)
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleNone;
}
// What to do when you click delete.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
//RootViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [formDataOne count];
} else {
return [formDataTwo count];
}
}
//RootViewController.m
- (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];
}
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
// Set up the cell...
NSString *cellValue;
if (indexPath.section == 0) {
cellValue = [formDataOne objectAtIndex:indexPath.row];
} else {
cellValue = [formDataTwo objectAtIndex:indexPath.row];
}
if (indexPath.section == 0) {
cell.text = #"";
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row == 0) {
addTitle = [[UITextField alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
addTitle.borderStyle = UITextBorderStyleNone;
addTitle.textColor = [UIColor blackColor]; //text color
addTitle.font = [UIFont systemFontOfSize:16.0]; //font size
addTitle.placeholder = #"Album Name"; //place holder
addTitle.backgroundColor = [UIColor clearColor]; //background color
addTitle.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
addTitle.keyboardType = UIKeyboardTypeDefault; // type of the keyboard
addTitle.returnKeyType = UIReturnKeyDone; // type of the return key
addTitle.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
addTitle.delegate = self; // let us be the delegate so we know when the keyboard's "Done" button is pressed
[cell.contentView addSubview:addTitle];
} else if (indexPath.row == 1) {
// Set up loading text and show it
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
myLabel.text = #"Private Album";
myLabel.textColor = [UIColor blackColor];
myLabel.textAlignment = UITextAlignmentLeft;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.font = [UIFont fontWithName:#"Helvetica" size: 16.0];
myLabel.numberOfLines = 0;
//[myLabel sizeToFit];
privateSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[privateSwitch addTarget:self action:#selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside];
[cell.contentView addSubview:privateSwitch];
//[privateSwitch setOn:NO animated:NO];
if ([howToDisplay isEqualToString:#"no"]) {
[privateSwitch setOn:NO animated:NO];
} else {
[privateSwitch setOn:YES animated:NO];
}
[cell.contentView addSubview:myLabel];
} else {
// Set up loading text and show it
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
myLabel.text = #"Comments";
myLabel.textColor = [UIColor blackColor];
myLabel.textAlignment = UITextAlignmentLeft;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.font = [UIFont fontWithName:#"Helvetica" size: 16.0];
myLabel.numberOfLines = 0;
//[myLabel sizeToFit];
[cell.contentView addSubview:myLabel];
commentsSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:commentsSwitch];
[commentsSwitch setOn:YES animated:NO];
}
} else {
//cell.text = cellValue;
UILabel *labelOne = [[UILabel alloc] initWithFrame:CGRectMake(48, 12, 130, 20)];
labelOne.text = cellValue;
labelOne.textColor = [UIColor blackColor];
[labelOne setFont:[UIFont boldSystemFontOfSize:16]];
labelOne.textAlignment = UITextAlignmentLeft;
labelOne.backgroundColor = [UIColor clearColor];
//labelOne.font = [UIFont fontWithName:#"Helvetica"];
labelOne.numberOfLines = 0;
[cell.contentView addSubview:labelOne];
if (indexPath.row == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
} else if (indexPath.row == 1) {
int countFacebook = [dataCeter.connectionFacebookArray count];
if (countFacebook == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
} else {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
} else if (indexPath.row == 2) {
//} else if (indexPath.row == 3) {
} else if (indexPath.row == 3) {
int countTumblr = [dataCeter.connectionTumblrArray count];
if (countTumblr == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
} else {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
} else if (indexPath.row == 4) {
} else if (indexPath.row == 5) {
} else {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
}
// Set imageView with correct thumbnail
UIImage *theImage;
if ([cellValue isEqualToString:#"Facebook"]) {
theImage = [UIImage imageNamed:#"icon_small_facebook.png"];
int countFacebook = [dataCeter.connectionFacebookArray count];
NSLog(#"facebook? %d // %#", countFacebook, dataCeter.connectionFacebookArray);
if (countFacebook != 0) {
facebookSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:facebookSwitch];
[facebookSwitch setOn:YES animated:NO];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
} else if ([cellValue isEqualToString:#"Twitter"]) {
theImage = [UIImage imageNamed:#"icon_small_twitter.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else if ([cellValue isEqualToString:#"Flickr"]) {
theImage = [UIImage imageNamed:#"icon_small_flickr.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else if ([cellValue isEqualToString:#"Tumblr"]) {
theImage = [UIImage imageNamed:#"icon_small_tumblr.png"];
int countTumblr = [dataCeter.connectionTumblrArray count];
if (countTumblr != 0) {
tumblrSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:tumblrSwitch];
[tumblrSwitch setOn:YES animated:NO];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
} else if ([cellValue isEqualToString:#"Email"]) {
theImage = [UIImage imageNamed:#"icon_small_email.png"];
int countEmail = [dataCeter.connectionEmailArray count];
} else if ([cellValue isEqualToString:#"MMS"]) {
theImage = [UIImage imageNamed:#"icon_small_mms.png"];
int countMMS = [dataCeter.connectionSMSArray count];
} else if ([cellValue isEqualToString:#"Photostream"]) {
theImage = [UIImage imageNamed:#"icon_small_photostream.png"];
cell.accessoryType = UITableViewCellAccessoryNone;
photostreamSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:photostreamSwitch];
[photostreamSwitch setOn:YES animated:NO];
} else {
theImage = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.imageView.image = theImage;
return cell;
}
Set your table view's separator style to UITableViewCellSeparatorStyleSingleLine. It's currently being set to UITableViewCellSeparatorStyleSingleLineEtched, which gives the effect of a doubled top border on the iPhone (it looks more detailed on iOS 5, and on iOS 3.2 and 4 on the iPad).
You're not insane, it looks like there is an extra pixel in there.
Try taking out "Sharing" and see if it still happens. Curious to see if the shadow is on "Sharing" or the table itself.
If that's the case, then you know your header view has a problem, not the table view.

Implementing toggle feature in a UIButton

I want to know how to add the toggling feature to a UIButton, something like the user taps a unselected button the button becomes selected and stays selected till the user taps it again there by making unselected like it was before.
I was thinking of making an IBAction which changes it from unselected to selected, how can I do that?
Heres what I tried:
-(IBAction)toggle {
//Toggle on implementation.
button.selected = YES;
button.highlighted = NO;
button.enabled = YES;
//Toggle off implementation.
if (button.highlighted == YES) {
button.selected = NO;
button.highlighted = YES;
button.enabled = NO;
}
}
Problem...
-(IBAction)toggleFav {
if (favButton == nil) {
UIImage *unselectedImage = [UIImage imageNamed:#"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:#"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
}
if([favButton isSelected]){
//Add to menu.
[favButton setSelected:NO];
} else {
//Remove from menu.
[favButton setSelected:YES];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIImage *unselectedImage = [UIImage imageNamed:#"unselected.png"];
UIImage *selectedImage = [UIImage imageNamed:#"selected.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setBackgroundImage:unselectedImage forState:UIControlStateNormal];
[b setBackgroundImage:selectedImage forState:UIControlStateSelected];
[b addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b setFrame:CGRectMake(0, 0, 40, 40)];
[cell.contentView addSubview:b];
}
return cell;
}
-(void) buttonPressed:(UIButton *)sender
{
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
Your toggleFav code doesn't make much sense.
if (favButton == nil) { checks, if favButton is present. But if you are wiring it up with IB, it should always been there at that point. And if it wasn't how could the button call this method? So do it like this:
-(void)viewDidLoad
{
//....
UIImage *unselectedImage = [UIImage imageNamed:#"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:#"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
//....
}
-(IBAction)toggleFav:(UIButton *)sender {
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
Here you'll find an example project, with a DetaiView, that holds a Button with the 2 states.
Note: I am saving the information of what button was selected in the NSUserDefaults. You should not do that. Instead you'll want to save it in the model. But as I dont have informations on your model, I am just using NSUserDefaults.
-(void)hitButton:(UIButton*)button
{
buttonOnFlag = !buttonOnFlag;
if( buttonFlag )
[self performSelector:#selector(setHighlight:) withObject:button afterDelay:0];
}
- (void)setHighlight:(UIButton*)button
{
button.highlighted = true;
}
Use button.highlighted property
You should code like this:
-(IBAction)toggle:(id)sender {
//Toggle on implementation.
if (sender.highlighted == NO)
{
sender.selected = YES;
sender.highlighted = NO;
sender.enabled = YES;
}
//Toggle off implementation.
else{
sender.selected = NO;
sender.highlighted = YES;
sender.enabled = NO;
}
}