How do I add a UIButton or UISwitch in tableView:viewForFooterInSection - objective-c

I'm trying to understand how to add a label with a UISwitch or other controller to a footer (or header) in a sectioned tableView. Any help would be greatly appreciated. Thank you in advance!

Okay, after searching and working at it I've done the following:
// Need to refactor so that the label is Public Sharing and Priviate Sharing and the actions work for each switch
- (UIView *) tableView: (UITableView *) tableView
viewForFooterInSection: (NSInteger) section
{
if (section == 0 || section == 1) {
CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
UIView* footerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, screenRect.size.width, 44.0)] autorelease];
footerView.autoresizesSubviews = YES;
footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
footerView.userInteractionEnabled = YES;
footerView.hidden = NO;
footerView.multipleTouchEnabled = NO;
footerView.opaque = NO;
footerView.contentMode = UIViewContentModeScaleToFill;
// Add the label
UILabel* footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(150.0, -5.0, 120.0, 45.0)];
footerLabel.backgroundColor = [UIColor clearColor];
footerLabel.opaque = NO;
footerLabel.text = #"Sharing";
footerLabel.textColor = [UIColor tableHeaderAndFooterColor];
footerLabel.highlightedTextColor = [UIColor tableHeaderAndFooterColor];
footerLabel.font = [UIFont boldSystemFontOfSize:17];
footerLabel.shadowColor = [UIColor whiteColor];
footerLabel.shadowOffset = CGSizeMake(0.0, 1.0);
[footerView addSubview: footerLabel];
[footerLabel release];
// Add the switch
UISwitch* footerSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(215.0, 5, 80.0, 45.0)];
[footerView addSubview: footerSwitch];
// Return the footerView
return footerView;
}
else return nil;
}
// Need to call to pad the footer height otherwise the footer collapses
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
switch (section) {
case 0:
case 1:
return 40.0;
default:
return 0.0;
}
}
I hope this is correct and if this helps anyone else please vote this up. Cheers!

i think you need to autorelease the uiview-

Related

Show UISearchController on UITableView scroll down

I have a UISearchController just over my UITableView and my table has many recrods. When a user goes to bottom in the table, he has to come back to top to see the search bar. Below you can see how I create the search bar:
- (void) showSearchBar {
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = nil;
[self.searchController.searchBar sizeToFit];
self.tableView.tableHeaderView = self.searchController.searchBar;
//self.sharedNavigationItem.titleView = _searchController.searchBar;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
self.definesPresentationContext = YES;
_searchController.hidesNavigationBarDuringPresentation = NO;
}
I was wondering how to show the search bar when I scroll down (go up) in the table and hide it back when I scroll up (go down) in the table even I am at the bottom of the table.
The search bar can be placed arbitrarily in the UI. Create a sibling view to the table view, placed -- for example -- above the table. Give that view a height constraint set initially to 44px and provide outlets to both the view and the constraint...
#property(weak,nonatomic) IBOutlet UIView *searchBarContainerView;
#property(weak,nonatomic) IBOutlet NSLayoutConstraint *searchBarHeightConstraint;
Now, your setup code changes to:
// ...
self.searchBarHeightConstraint.constant = self.searchController.searchBar.bounds.size.height;
[self.searchBarContainerView addSubview:self.searchController.searchBar];
// ...
If you make the header stay at top, then the search field should stay visible
UITableViewStylePlain: A plain table view. Any section headers or footers are displayed as inline separators and float when the table view is scrolled.
UITableViewStyleGrouped: A table view whose sections present distinct groups of rows. The section headers and footers do not float.
I trying to help you out with what I did, hope it helps you.
This is how I added my label in header view of table view, I tried to replace it by your search controller;
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = CGRectMake(0, 0, tableView.frame.size.width, 40);
UIView *view = [[UIView alloc] initWithFrame:frame];
view.backgroundColor = [UIColor clearColor];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = nil;
[self.searchController.searchBar sizeToFit];
[view addSubview:_searchController];
view.tag = 123;
return view;
}
If you wish to hide effect at complete end of dragging move use below method;
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset{
if (velocity.y > 0){
NSLog(#"up");
[self.view viewWithTag:123].hidden = true;
}
if (velocity.y < 0){
NSLog(#"down");
[self.view viewWithTag:123].hidden = false;
}
And for immediate changes of scrolling the tableview use below method :
-(void)scrollViewDidScroll:(UIScrollView *)scrollView //working delegate
{
if ([scrollView.panGestureRecognizer translationInView:scrollView].y > 0) {
NSLog(#"down");
[self.view viewWithTag:123].hidden = false;
} else {
NSLog(#"up");
[self.view viewWithTag:123].hidden = true;
}
}
After some searching I thought of some new answer, hope it helps you!
To identify direction of Scroll:
BOOL showSearch;
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if ([scrollView.panGestureRecognizer translationInView:scrollView].y > 0) {
// down
showSearch = true;
} else {
// up
showSearch = false;
}
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset{
if (showSearch) {
[self addSearch];
}
else {
[self removeSearch];
}
[_tableView reloadData];
}
To add & remove SearchController:
-(void)addSearch {
if (!_searchController){
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
[_searchController.searchBar sizeToFit];
_tableView.tableHeaderView = _searchController.searchBar;
_searchController.delegate = self;
_searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
_searchController.active = NO;
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
_tableView.tableHeaderView = _searchController.searchBar;
_searchController.searchBar.delegate = self;
}
}
-(void)removeSearch {
_searchController.active = NO;
[_searchController removeFromParentViewController];
_searchController = nil;
_tableView.tableHeaderView = nil;
}

UIScrollView and UIPageControl, what am I doing wrong?

I have a class which is predefining some labels and binding their values in a UIScrollView.
I've managed to show those labels, but now I'm stuck at putting a label at the 2nd part of the ScrollView.
I've pushed my project to gitHub.
I can change the label's place on the already visible part, but I must be overlooking something.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = _detail.name;
UIColor *bgColor = [UIColor blackColor];
UIColor *txtColor = [UIColor grayColor];
CGRect frame;
frame.origin.x = 0;
frame.origin.y = 0;
frame.size.width = _scrollView.frame.size.width *2;
NSString *phoneNr = (_detail.phoneNr == nil) ? #"Not specified" : _detail.phoneNr;
_telLabel = [self prepareLabel:phoneNr textColor:txtColor bgColor:bgColor page:0 y:telNrYAxis];
_webLabel = [self prepareLabel:#"Visit website" textColor:txtColor bgColor:bgColor page:0 y:websiteYAxis];
_detail.address = [_detail.address stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\n\t "]];
NSArray *addressArrComponents = [_detail.address componentsSeparatedByString:#","] ;
_addressLabel = [self prepareLabel:[addressArrComponents componentsJoinedByString:#"\n"] textColor:txtColor bgColor:bgColor page:0 y:addressYAxis];
UILabel *lbl = [self prepareLabel:#"Derp" textColor:txtColor bgColor:bgColor page:1 y:0];
_detailView = [[UIView alloc] initWithFrame:frame];
_detailView.backgroundColor = [UIColor blackColor];
[_detailView addSubview:_webLabel];
[_detailView addSubview:_addressLabel];
[_detailView addSubview:_telLabel];
[_detailView addSubview:lbl];
[_scrollView addSubview:_detailView];
NSLog(#"%f",self.view.frame.size.height - (_scrollView.frame.origin.y + _scrollView.frame.size.height) );
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height - 250 , self.view.frame.size.width/4, 120)];
_pageControl.numberOfPages=2;
_pageControl.currentPage=0;
[_pageControl addTarget:self action:#selector(pageChange:) forControlEvents:UIControlEventTouchDown];
_scrollView.contentSize = CGSizeMake(800,800);
_scrollView.delegate=self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.pagingEnabled=YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
[self pageChange:0];
[self.view addSubview:_pageControl];
// Do any additional setup after loading the view.
}
-(UILabel*)prepareLabel:(NSString*) text textColor:(UIColor*)textColor bgColor:(UIColor*)backgroundColor page:(int)page y:(int) yPos{
int lines = [[text componentsSeparatedByString:#"\n"] count];
CGRect labelFrame = CGRectMake(_detailView.frame.size.width * page +20,yPos,self.view.frame.size.width, [UIFont systemFontSize]*lines);
UILabel *returnLabel = [[UILabel alloc] initWithFrame:labelFrame];
returnLabel.text = text;
returnLabel.backgroundColor = backgroundColor;
returnLabel.textColor = textColor;
[returnLabel setNumberOfLines:lines];
[returnLabel sizeToFit];
return returnLabel;
}
- (void)loadScrollViewWithPage:(int)page {
NSLog(#"Derped");
}
-(IBAction)pageChange:(id)sender{
int page=_pageControl.currentPage;
CGRect frame = _scrollView.frame;
frame.origin.x = _scrollView.frame.size.width * page;
frame.origin.y = 0;
//CGRect frame= (page == 0) ? _detailFrame : _reviewFrame;
NSLog(#"%f",frame.origin.x);
[_scrollView scrollRectToVisible:frame animated:YES];
}
The delegate -(IBAction)pageChange:(id)sender gets fired, but I must be doing something wrong with the frames somewhere :s
Please take a look!
Try to implement this method may help you :
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = self.scrollView.frame.size.width;
float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
self.pageControl.currentPage = page;
}

UITableViewCell with alternate background color in customized cells

I'd like the background to of my UITableViewCells to have a different color every two cells displayed, but when I scroll down and back, they all get the same color. How can I get this effect knowing that my cells have different contentView size (according to their content) ?
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
#define NAME_CELL_HEIGHT 20.0f
#import "CartCell.h"
#implementation CartCell
#synthesize nameLabel = _nameLabel;
#synthesize ingredientsLabel = _ingredientsLabel;
#synthesize myStore;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
myStore = [Store sharedStore];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.nameLabel = nil;
self.ingredientsLabel = nil;
// SET "NAME" CELL
self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.nameLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.nameLabel setMinimumFontSize:FONT_SIZE];
[self.nameLabel setNumberOfLines:1];
[self.nameLabel setTag:1];
self.nameLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
[self.nameLabel sizeToFit];
self.nameLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.nameLabel];
// SET "INGREDIENTS" CELL
self.ingredientsLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.ingredientsLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.ingredientsLabel setMinimumFontSize:FONT_SIZE];
[self.ingredientsLabel setNumberOfLines:0];
[self.ingredientsLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[self.ingredientsLabel setTag:2];
self.ingredientsLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.ingredientsLabel];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = NO;
} else {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:268.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
UPDATE:
I'm know trying to set it in cellForRowAtIndexPath as it was suggested, but I get the same result: scrolling down worked fine the first time, but then scrolling up again messed up the cells background color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CartCell";
CartCell *cell = (CartCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Recipes *info = [_fetchedResultsController objectAtIndexPath:indexPath];
if (cell == nil)
{
cell = [[CartCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// if (!cell.nameLabel) {
// cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// // cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// }
// if (!cell.ingredientsLabel)
// cell.ingredientsLabel = (UILabel*)[cell viewWithTag:2];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [info.ingredients sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[cell.nameLabel setFrame:CGRectMake(10, 10, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), NAME_CELL_HEIGHT)];
[cell.ingredientsLabel setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN + NAME_CELL_HEIGHT, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
// SETTING TEXT CONTENT
cell.nameLabel.text = info.name;
cell.ingredientsLabel.text = info.ingredients;
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1];
// cell.backgroundView = lab;
// ingredientsLabel.backgroundColor = [UIColor clearColor];
// nameLabel.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
// [cell setBackgroundColor: [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1]];
// [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];
myStore.cellBackgroundShouldBeLight = NO;
} else {
// cell.contentView.tag = 2;
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
return cell;
}
It is very simple, the indexPath tells you everything you need to know. If the indexPath.row is even then use one color. If the indexPath.row is odd use a different color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
…
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (indexPath.row % 2) {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
} else {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
}
…
return cell;
}
Your method is having problems because blindly assuming cells will be asked for in alternating pairs is a bad assumption. The tableView could ask for cells in any order is chooses. In your example, I believe cells could be asked for as follows. First, 0, 1,…, 9 are asked for. Next, you scroll down and 10, 11, and 12 are fetched. At this point, 0, 1, and 2 have gone off the screen. You scroll back up and 2 is asked for, but oh no, your model is on an odd number alternation, so you get the wrong color.
Use the -willDisplayCell method.
- (void)tableView: (UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath {
if (indexPath.row %2) { //change the "%2" depending on how many cells you want alternating.
UIColor *altCellColor = [UIColor colorWithRed:255/255.0 green:237/255.0 blue:227/255.0 alpha:1.0]; //this can be changed, at the moment it sets the background color to red.
cell.backgroundColor = altCellColor;
}
else if (indexPath.row %2) {
UIColor *altCellColor2 = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.0]; //this can be changed, at the moment it sets the background color to white.
cell.backgroundColor = altCellColor2;
}
}
The appropriate place to change your cell's background color would be the "cellForRowAtIndexPath:" method, where the cells data gets filled out and returned to the table view.
One way to do this would be: When the data goes into the cell, change the background color depending on what row you're on.
Put the color on the cellForRowAtIndexPath: don't set on custom cell.
Take a look what I use to customize my table
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if USE_CUSTOM_DRAWING
const NSInteger TOP_LABEL_TAG = 1001;
const NSInteger BOTTOM_LABEL_TAG = 1002;
UILabel *topLabel;
UILabel *bottomLabel;
#endif
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//
// Create the cell.
//
cell =
[[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
#if USE_CUSTOM_DRAWING
UIImage *indicatorImage = [UIImage imageNamed:#"indicator.png"];
cell.accessoryView =
[[[UIImageView alloc]
initWithImage:indicatorImage]
autorelease];
const CGFloat LABEL_HEIGHT = 20;
UIImage *image = [UIImage imageNamed:#"imageA.png"];
//
// Create the label for the top row of text
//
topLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:topLabel];
//
// Configure the properties for the text that are the same on every row
//
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
//
// Create the label for the top row of text
//
bottomLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT) + LABEL_HEIGHT,
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:bottomLabel];
//
// Configure the properties for the text that are the same on every row
//
bottomLabel.tag = BOTTOM_LABEL_TAG;
bottomLabel.backgroundColor = [UIColor clearColor];
bottomLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
for (UIView *sub in [cell.contentView subviews]) {
// if([sub class] == [UITableViewCellContentView class])
NSLog(#"this is uilabel %#",[sub class]);
}
topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
}
topLabel.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
bottomLabel.text = [NSString stringWithFormat:#"Some other information.", [indexPath row]];
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"topRow.png"];
selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"bottomRow.png"];
selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"middleRow.png"];
selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
// cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:rowBackground];
// cell.selectedBackgroundView.backgroundColor = [UIColor colorWithPatternImage:selectionBackground];
//
// Here I set an image based on the row. This is just to have something
// colorful to show on each row.
//
if ((row % 3) == 0)
{
cell.imageView.image = [UIImage imageNamed:#"imageA.png"];
}
else if ((row % 3) == 1)
{
cell.imageView.image = [UIImage imageNamed:#"imageB.png"];
}
else
{
cell.imageView.image = [UIImage imageNamed:#"imageC.png"];
}
#else
cell.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
#endif
return cell;
}
past it after all #import lines
#define USE_CUSTOM_DRAWING 1
Heading ##Simplest way of changing alternate colors
if(indexPath.row%2) {
cell.backgroundColor=[UIColor nameUrColor] //brownColor, yellowColor, blueColor
} else {
cell.backgroundColor=[UIColor nameAnotherColor]
}
if(cell.contentView)
{
[cell.nameLbl setFont:[UIFont systemFontOfSize:24]];
int red_value = arc4random() % 210;
int green_value = arc4random() % 210;
int blue_value = arc4random() % 210;
cell.contentView.backgroundColor = [UIColor colorWithRed:red_value/255.0 green:green_value/255.0 blue:blue_value/255.0 alpha:0.6];
}

Hijack "swipe to next page" in UIScrollView

i'd like to prevent scrolling on the 3rd page of my UIScrollview and "hijack the swipe" gesture to trigger sth. else. Afer this action I'd like to reactive scrolling.
This does not work.
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
if(scrollView.contentOffset.x == self.view.frame.size.width * 2 ) {
// disable scrolling
scrollView.scrollEnabled = NO;
}
}
// hijack the next scrolling event
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
This delegate is not called when scrollEnabled = NO
Thanks for helping
EDIT EventHandler ist not called ;-(
- (void)viewDidLoad
{
[super viewDidLoad];
// Default background color
self.view.backgroundColor = [UIColor redColor];
// Create scroll view
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
recognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[scrollView addGestureRecognizer:recognizer];
[recognizer release];
[scrollView delaysContentTouches];
// Create subviews (pages)
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
// x pos
CGFloat yOrigin = i * self.view.frame.size.width;
// Create subview and add to scrollView
UIView *pageView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
pageView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[scrollView addSubview:pageView];
[pageView release];
}
// Set contentsize
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
// Add scrollView to view and release
[self.view addSubview:scrollView];
[scrollView release];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
NSLog(#"swipe!!!!");
scrollView.scrollEnabled = YES;
}
If you disable the scroll view:
scrollView.scrollEnabled = NO;
it is unavoidable that the delegate method is not called, so you need an alternative way to handle the swipe while in hijack mode. One thing you could try is using an UISwipeGestureRecognizer: instead of simply disabling scrolling, you could associate a UISwipeGestureRecognizer to you view and handle the swipe from the handler method:
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
recognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:recognizer];
and in handleSwipeFrom you would reenable scrolling:
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
// do your hijack here
scrollView.scrollEnabled = YES;
}

objective c - hide a custom annotation view

I want to have a custom Annotation view that behaves exactly as the standard one, but mine needs to have an image inside and several texts, that's why I've implemented the tutorial on http://developer.apple.com/library/ios/#samplecode/WeatherMap/Introduction/Intro.html
But my problem is that I want the annotation view to hide and just show a pin, same thing as the default annotation view behaves but all annotations are showing and I cant figure out a way to hide them.
Any ideas?
Thanks.
[EDIT]
My current implementation of viewForAnnotation is:
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation{
NSLog(#"Item añadido");
static NSString *AnnotationViewID = #"annotationViewID";
CustomMKAnnotationView *annotationView =
(CustomMKAnnotationView *)[mapa dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil)
{
annotationView = [[[CustomMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.annotation = annotation;
return annotationView;
}
Becuase I need the standard bubble but with an image and a couple of UILabels. But I would like to keep the standard behaviour, that is, there's a pin when the bubble is not showing, and when you tap it shows the bubble. The content of my custom bubble is implemented in "CustomMKAnnotationView".
Which is as follows:
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if (self != nil)
{
CGRect frame = self.frame;
frame.size = CGSizeMake(10.0, 10.0);
self.frame = frame;
// self. = [super pincolor];
self.backgroundColor = [UIColor clearColor];
self.centerOffset = CGPointMake(10.0, 10.0);
}
return self;
}
- (void)drawRect:(CGRect)rect{
CustomMKAnnotation *custom = (CustomMKAnnotation *)self.annotation;
if (custom != nil)
{
NSLog(#"El nombre es: %#", [custom nombre]);
UILabel *nombre = [[UILabel alloc]init];
UILabel *media = [[UILabel alloc]init];
PDColoredProgressView *barrita = [[PDColoredProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
[barrita setTintColor:[UIColor colorWithRed:0.6 green:0.83 blue:0.91 alpha:1.0f]];
nombre.textColor = [UIColor whiteColor];
media.textColor = [UIColor whiteColor];
nombre.font = [UIFont fontWithName:#"DIN-Bold" size:14];
media.font = [UIFont fontWithName:#"DIN-Medium" size:12];
CGSize size = [[custom nombre] sizeWithFont:nombre.font constrainedToSize:CGSizeMake(300, 20) lineBreakMode:nombre.lineBreakMode];
NSLog(#"el ancho es: %f y alto %f", size.width, size.height);
nombre.backgroundColor = [UIColor clearColor];
media.backgroundColor = [UIColor clearColor];
nombre.text = [custom nombre];
barrita.progress = [custom gente];
media.text = [NSString stringWithFormat:#"Media %# años", [custom media]];
UIImageView *fondo = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"bubble_map.png"]];
nombre.frame = CGRectMake(10, 10, size.width, size.height);
media.frame = CGRectMake(10, size.height + 10, size.width, size.height);
barrita.frame = CGRectMake(10, media.frame.origin.y + 20, size.width, 10);
fondo.frame = CGRectMake(-((size.width+ 20.0f)/2), -((size.height +10)*2 + 20)-10, size.width+ 20.0f, (size.height +10)*2 + 20);
fondo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
nombre.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[fondo addSubview:nombre];
[fondo addSubview:media];
[fondo addSubview:barrita];
[self addSubview:fondo];
[fondo release];
[nombre release];
[media release];
}
}
If you mean hiding the details of pin, have you tried creating a custom MKPinAnnotationView and set its property of canShowCallout=NO; ?
In your mapview delegate method :
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView*pinView;
if([annotation isKindOfClass:[<yourannotationclass> class]])
{
static NSString*annoIdentifier=#"AnnotationIdentifier";
pinView=(MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:annoIdentifier];
if(pinView==nil)
{
pinView=[[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annoIdentifier]autorelease ];
}
pinView.animatesDrop=NO;
pinView.canShowCallout=NO;
pinView.pinColor=MKPinAnnotationColorRed;
}
return pinView;
}