How to implement PSCollectionView in iphone App? - iphone

In my application i have six button which need to be place on pscollectionview.
i have placed pscollectionview in app but i am not abel to use the datasource and delegate method?
can any one come up with this example will be helpfull?
following is my code:
- (void)viewDidLoad
{
self.collectionView = [[PSCollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
self.collectionView.delegate = self;
self.collectionView.collectionViewDelegate = self;
self.collectionView.collectionViewDataSource = self;
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.collectionView];
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn1.frame = CGRectMake(10, 30, 140, 130);
[self.collectionView addSubview:btn1];
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn2.frame = CGRectMake(170, 30, 140, 130);
[self.collectionView addSubview:btn2];
UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn3.frame = CGRectMake(10, 180, 140, 130);
[self.collectionView addSubview:btn3];
UIButton *btn4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn4.frame = CGRectMake(170, 180, 140, 130);
[self.collectionView addSubview:btn4];
UILabel *loadingLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 100, 50, 20)];
loadingLabel.text = #"Loading...";
loadingLabel.textAlignment = UITextAlignmentCenter;
[self.collectionView addSubview:loadingLabel];
//self.collectionView.loadingView = loadingLabel;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)numberOfViewsInCollectionView:(PSCollectionView *)collectionView {
return 1;
}
- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView viewAtIndex:(NSInteger)index {
}
- (CGFloat)heightForViewAtIndex:(NSInteger)index {
NSDictionary *item = [self.items objectAtIndex:index];
return [NDACCustomView heightForViewWithObject:item inColumnWidth:self.collectionView.colWidth];
}
- (void)collectionView:(PSCollectionView *)collectionView didSelectView:(PSCollectionViewCell *)view atIndex:(NSInteger)index {
// NSDictionary *item = [self.items objectAtIndex:index];
// You can do something when the user taps on a collectionViewCell here
}

PSCollectionView's delegate method has been updated after this question posted.
Visit https://github.com/ptshih/PSCollectionView.
Just share my code here.
- (void)viewDidLoad
{
self.collectionView = [[PSCollectionView alloc] initWithFrame:self.view.frame];
self.collectionView.delegate = self; // This is for UIScrollViewDelegate
self.collectionView.collectionViewDelegate = self;
self.collectionView.collectionViewDataSource = self;
self.collectionView.backgroundColor = [UIColor clearColor];
self.collectionView.autoresizingMask = ~UIViewAutoresizingNone;
// Specify number of columns for both iPhone and iPad
self.collectionView.numColsPortrait = 3;
self.collectionView.numColsLandscape = 4;
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg.png"]];
[self.view addSubview:_collectionView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (Class)collectionView:(PSCollectionView *)collectionView cellClassForRowAtIndex:(NSInteger)index {
return [MCCollectionViewCell class];
}
- (NSInteger)numberOfRowsInCollectionView:(PSCollectionView *)collectionView {
return 30;
}
- (UIView *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index {
MCCollectionViewCell *cell = (MCCollectionViewCell *)[_collectionView dequeueReusableViewForClass:[MCCollectionViewCell class]];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MCCollectionViewCell" owner:self options:nil];
cell = (MCCollectionViewCell *)[nib objectAtIndex:0];
}
NSOperationQueue *imageQueue = [[NSOperationQueue alloc] init];
[imageQueue addOperation:[NSBlockOperation blockOperationWithBlock:^{
int r = arc4random() % 3;
NSString *imageName = [NSString stringWithFormat:#"image%d", r];
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:#"jpg"]];
[[NSOperationQueue mainQueue] addOperation:[NSBlockOperation blockOperationWithBlock:^{
cell.previewImageView.image = image;
cell.titleLabel.text = imageName;
}]];
}]];
return cell;
}
- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index {
return 290.0;
}

Related

Add another view in GMGridView

Hello all,
I have to add one more view in cell of GMGridView. But i am unable to do this because i have to drag my label from view to view1.
My code is :
- (GMGridViewCell *)GMGridView:(GMGridView *)gridView1 cellForItemAtIndex:(NSInteger)index
{
// set size based on orientation
CGSize size = [self GMGridView:gridView sizeForItemsInInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
GMGridViewCell *cell = [gridView dequeueReusableCell];
if (!cell)
{
cell = [[[GMGridViewCell alloc]init]autorelease];
//one view
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
view.backgroundColor = [UIColor redColor];
view.layer.masksToBounds = NO;
view.layer.cornerRadius = 2;
cell.contentView = view;
//another view
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 80, size.width, size.height)];
view1.backgroundColor = [UIColor yellowColor];
view1.layer.masksToBounds = NO;
view1.layer.cornerRadius = 2;
cell.contentView = view1;
}
[[cell.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
// allocate label
UILabel *label = [[UILabel alloc] initWithFrame:cell.contentView.bounds];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
label.text = (NSString *)[self.currentData objectAtIndex:index];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.font = [UIFont boldSystemFontOfSize:20];
[cell.contentView addSubview:label];
return cell;
}
height of cell is 200. but still it shows only one view.
Loading Two types of Cell in GMGridView
This is your Solution, it works as charm..
First Do this Exactly
-(void)prepareExhibitor
{
NSInteger spacing = 1.0;
CGRect rect=self.view.frame;
rect.origin=CGPointMake(0, 0);
self.gmGridView = [[GMGridView alloc] initWithFrame:rect];
self.gmGridView.backgroundColor = [UIColor clearColor];
self.gmGridView.centerGrid=NO;
self.gmGridView.style = GMGridViewStylePush;
self.gmGridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontal];
self.gmGridView.showsHorizontalScrollIndicator=FALSE;
self.gmGridView.clipsToBounds=YES;
self.gmGridView.itemSpacing = spacing;
self.gmGridView.minEdgeInsets = UIEdgeInsetsMake(0,30, 0, 0);
[self.viewNewsHeadline addSubview:self.gmGridView];
self.gmGridView.actionDelegate = self;
self.gmGridView.dataSource = self;
self.gmGridView.mainSuperView = self.superView;
}
Then Write this accordingly as per your Code
- (GMGridViewCell *)GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index
{
GMGridViewCell *cell = [gridView dequeueReusableCell];
NewsCell_iPad *view;
UIViewController *controller;
if (!cell)
{
// [self removeGrid];
cell = [[GMGridViewCell alloc] init];
if(index%2==0)
{
controller=[[UIViewController alloc] initWithNibName:#"NewsCellTypeA_iPad" bundle:nil];
}
else
{
controller=[[UIViewController alloc] initWithNibName:#"NewsCellTypeB_iPad" bundle:nil];
}
if(!view)
{
view=(NewsCell_iPad *)controller.view;
}
cell.layer.masksToBounds = NO;
cell.contentView = view;
}
NewsCell_iPad *newsView=(NewsCell_iPad *)cell.contentView;
newsView.news=[self.arrNews objectAtIndex:index];
[self hideGradientBackground:newsView.webViewDetailedNews];
[newsView downloadImage];
[newsView loadWebView];
// NSLog(#"cell=%d ,arr image index=%#",index,[self.arrNews objectAtIndex:index]);
return cell;
}

iPhone-Grouped Table View adding two radio buttons for each row

I want to display two radio buttons in each row and i need to set action for two buttons i was facing problem in setting the actions and display text and radio buttons in correct position for each row, If some one help please.
Here is my code
Thanks in advance
.h file
#import <UIKit/UIKit.h>
//#class CustomCellQuestionnaireList;
#interface QuestionnaireListView : UIViewController <UITableViewDataSource, UITableViewDelegate,UINavigationControllerDelegate,UISearchBarDelegate>
{
//NSMutableArray *dataArray;
UITableView *theTableView;
UILabel *lbl_child;
UILabel *lbl_title;
UILabel *lbl_time;
NSMutableArray *tableData;//will be storing data that will be displayed in table
NSMutableArray *tableSubData;
//NSMutableArray *tableTitleArray;
//CustomCellQuestionnaireList *cell;
IBOutlet UIButton *myButton;
IBOutlet UIButton *myButton2;
BOOL isSelected;
IBOutlet UIView *view1;
IBOutlet UIBarButtonItem *saveBtn;
IBOutlet UIBarButtonItem *discardBtn;
IBOutlet UIBarButtonItem *okBtn;
//IBOutlet UIToolbar *m_toolBar;
//IBOutlet UIToolbar *m_okToolBar;
}
#property (nonatomic,retain) IBOutlet UILabel *lbl_child;
#property (nonatomic,retain) IBOutlet UILabel *lbl_title;
#property (nonatomic,retain) IBOutlet UILabel *lbl_time;
#property (nonatomic,retain) IBOutlet UITableView * theTableView;
//#property(nonatomic,retain) NSMutableArray *dataArray;
#property(nonatomic, retain) NSMutableArray *tableData;
#property(nonatomic, retain)NSMutableArray *tableSubData;
#property(nonatomic, retain)UIView *view1;
#property(nonatomic, retain)UIBarButtonItem *saveBtn;
#property(nonatomic, retain)UIBarButtonItem *discardBtn;
#property(nonatomic, retain)UIBarButtonItem *okBtn;
//#property(nonatomic, retain)UIToolbar *m_toolBar;
//#property(nonatomic, retain)UIToolbar *m_okToolBar;
- (IBAction)onClickLeftArrow;
- (IBAction)onClickRightArrow;
//- (IBAction)savePressed:(id)sender;
- (IBAction)selectRadioButon:(UIButton *)button;
//-(IBAction)okPressed:(id)sender;
#end
.m file
#implementation QuestionnaireListView
#synthesize tableData, tableSubData;
#synthesize theTableView;
//#synthesize dataArray;
#synthesize lbl_child;
#synthesize lbl_title;
#synthesize lbl_time;
#synthesize view1;
#synthesize saveBtn;
#synthesize discardBtn;
#synthesize okBtn;
//#synthesize m_toolBar;
//#synthesize m_okToolBar;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:#"saveBtn.png"] forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(0, 0, 66, 34)];
[button1 addTarget:self action:#selector(saveBtn:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:#"Save" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:button1];
NSMutableArray *toolBarItems = [[[NSMutableArray alloc] init] autorelease];
[toolBarItems addObject:barButtonItem1];
//[self setToolbarItems:toolBarItems];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:#"okBtn.png"] forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(100, 0, 66, 34)];
//[button2 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
//[button2 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button2];
[toolBarItems addObject:barButtonItem2];
button2.hidden = YES;
//[self setToolbarItems:toolBarItems];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setImage:[UIImage imageNamed:#"okBtn.png"] forState:UIControlStateNormal];
[button3 setFrame:CGRectMake(150, 0, 66, 34)];
//[button4 addTarget:self action:#selector(okBtn:) forControlEvents:UIControlEventTouchUpInside];
//[button4 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button3];
[toolBarItems addObject:barButtonItem3];
button3.hidden = YES;
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 setImage:[UIImage imageNamed:#"discardBtn.png"] forState:UIControlStateNormal];
[button4 setFrame:CGRectMake(200, 0, 66, 34)];
[button4 addTarget:self action:#selector(discardBtn:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:#"Discard" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem4 = [[UIBarButtonItem alloc] initWithCustomView:button4];
[toolBarItems addObject:barButtonItem4];
[self setToolbarItems:toolBarItems];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//[self.theTableView.layer setCornerRadius:30.0];
// create button
//UIButton* logOutButton = [UIButton buttonWithType:101]; // left-pointing shape!
UIButton *logOutButton = [UIButton buttonWithType:100];
[logOutButton setImage:[UIImage imageNamed:#"exitBtn.png"] forState:UIControlStateNormal];
[logOutButton addTarget:self action:#selector(logoutButtonTouched) forControlEvents:UIControlEventTouchUpInside];
[logOutButton setTitle:#"Logout" forState:UIControlStateNormal];
UIBarButtonItem* logOutItem = [[UIBarButtonItem alloc] initWithCustomView:logOutButton];
self.navigationItem.leftBarButtonItem = logOutItem;
[lbl_title setText:#"Store View"];
[lbl_title setTextColor:[UIColor whiteColor]];
//NSString *date = [[NSDate date] dateFormat];
NSString *date = [NSDate date];
NSLog(#"date:%#",date);
[lbl_time setText:[NSString stringWithFormat:#"%#",date]];
[lbl_time setTextColor:[UIColor whiteColor]];
// add to toolbar, or to a navbar (you should only have one of these!)
//[toolbar setItems:[NSArray arrayWithObject:backItem]];
//tableTitleArray = [[NSMutableArray alloc]init];
// [tableTitleArray addObject:#"General"];
// [tableTitleArray addObject:#"Product"];
tableData = [[NSMutableArray alloc] init];
[tableData addObject:#"Is the floor clean?"];
[tableData addObject:#"Are the food items stacked in freezer?"];
tableSubData = [[NSMutableArray alloc] init];
[tableData addObject:#"Has the snow been cleared at the entrance?"];
[tableData addObject:#"Are milk products available"];
view1.hidden = YES;
//m_okToolBar.hidden= YES;
//m_toolBar.barStyle = UIBarStyleBlackTranslucent;
//m_toolBar.tintColor = [UIColor blackColor]; m_toolBar.alpha = 0.7;
//UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"nextBtn.png" style:UIBarButtonItemStyleBordered target:self action:#selector(customButtonHandler:)]];
// btn.frame = CGRectMake(5, 20, 30, 30);
//[btn release];
}
-(void)saveBtn:(id)sender {
NSLog(#"Button pressed");
view1.hidden = NO;
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:#"saveBtn.png"] forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(0, 0, 105, 34)];
//[button1 addTarget:self action:#selector(saveBtn:) forControlEvents:UIControlEventTouchUpInside];
//[button1 setTitle:#"Save" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:button1];
NSMutableArray *toolBarItems = [[[NSMutableArray alloc] init] autorelease];
[toolBarItems addObject:barButtonItem1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:#"okBtn.png"] forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(0, 0, 66, 34)];
[button2 addTarget:self action:#selector(okBtn:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:#"OK" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button2];
[toolBarItems addObject:barButtonItem2];
[self setToolbarItems:toolBarItems];
button1.hidden = YES;
button2.hidden = NO;
button3.hidden = YES;
button4.hidden = YES;
}
-(void)okBtn:(id)sender {
view1.hidden = YES;
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:3] animated:YES];
}
//-(void)viewWillAppear:(BOOL)animated
//{
//
// //VizueraQAppDelegate *appDelegate = (VizueraQAppDelegate *)[[UIApplication sharedApplication] delegate];
// //[appDelegate RefreshIndexArray];
//
//}
- (void)logoutButtonTouched {
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}
- (IBAction)onClickLeftArrow {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickRightArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// release the array
// self.dataArray = nil;
// tableData = nil;
}
- (void)dealloc
{
//[cell release];
[tableData release];
[tableSubData release];
[super dealloc];
}
#pragma mark - UIViewController delegate methods
- (void)didReceiveMemoryWarning
{
// invoke super's implementation to do the Right Thing, but also release the input controller since we can do that
// In practice this is unlikely to be used in this application, and it would be of little benefit,
// but the principle is the important thing.
//
[super didReceiveMemoryWarning];
}
//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
// return YES;
//}
#pragma mark - UITableView delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableData!=nil && tableSubData!=nil) {
return 2;
}
else {
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return [tableData count];
}
else {
return [tableSubData count];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 74;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//return ([NSString stringWithFormat:#"%#", [tableTitleArray objectAtIndex:section]]);
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *returnString = #"";
if (tableData!=nil && section == 0) {
returnString = #"General";
}
else if(section == 1){
returnString = #"Product";
}
return returnString;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:kCustomCellID];
//CustomCell *cell = (CustomCell *)[theTableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:kCustomCellID] autorelease];
//cell = (CustomCell *)[[[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCustomCellID] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.tag=[indexPath row];
NSInteger tagCount;
myButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 48, 20, 20)];
[myButton setImage:[UIImage imageNamed:#"radioBtn.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(selectRadioButon:) forControlEvents:UIControlEventTouchUpInside];
myButton.tag = ++tagCount;
[cell.contentView addSubview:myButton];
tagCount++;
myButton2 = [[UIButton alloc]initWithFrame:CGRectMake(100, 48, 20, 20)];
[myButton2 setImage:[UIImage imageNamed:#"radioBtn.png"] forState:UIControlStateNormal];
[myButton2 addTarget:self action:#selector(selectRadioButon:) forControlEvents:UIControlEventTouchUpInside];
myButton2.tag = tagCount;
[cell.contentView addSubview:myButton2];
tagCount++;
/*UILabel *m_label = [[UILabel alloc] init];
m_label.text = #"Yes";
m_label.textColor = [UIColor redColor];
m_label.frame = CGRectMake(15, 48, 40, 40);
[m_label release]; */
CGRect labelRect = CGRectMake(35, 49, 30, 15);
UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
//label.backgroundColor = [UIColor redColor];
label.text = #"Yes";
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont boldSystemFontOfSize:14];
label.tag = 10;
[cell.contentView addSubview:label];
[label release];
CGRect labelRect1 = CGRectMake(125, 50, 30, 15);
UILabel *label1 = [[UILabel alloc] initWithFrame:labelRect1];
//label.backgroundColor = [UIColor redColor];
label1.text = #"No";
label1.textAlignment = UITextAlignmentLeft;
label1.font = [UIFont boldSystemFontOfSize:14];
label1.tag = 10;
[cell.contentView addSubview:label1];
[label1 release];
}
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if([tableData count]>indexPath.row)
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.textLabel.frame = CGRectMake(0, 0, 20, 20);
return cell;
}
- (IBAction)selectRadioButon:(UIButton *)button{
for (UIButton *but in [self.view subviews]) {
if ([but isKindOfClass:[UIButton class]] && ![but isEqual:button]) {
[but setSelected:NO];
}
}
if (!button.selected) {
button.selected = !button.selected;
}
if (isSelected) {
[button setImage:[UIImage imageNamed:#"radioBtn.png"] forState:UIControlStateNormal];
isSelected = NO;
}
else {
[button setImage:[UIImage imageNamed:#"radioBtn_active.png"] forState:UIControlStateNormal];
isSelected = YES;
}
}
Keep your "initWithFrame" codes inside the if(cell == nil) { } for when you're drawing your table cells and move all the "setting" UI elements outside that if.
See my code example here:
Can't Change Transparent BG in Custom UITableViewCell (Grouped Table View)

Background image not displayed on UIView

I have a class that implements "UIView" and inside - (void)drawRect:(CGRect)rect method I add some custom buttons to self. Inside a UIViewController I declare an instance of this view and i add it to self.view.
If i do this in - (void)viewDidLoad, everything works perfect, but if I create a method that is called when I push a button, and add that view to self.view, the buttons background is displayed after a few second. Till then only the name of the button appears written in white.
What do i do wrong?
Regards
#implementation CustomButton
#synthesize isPressed, buttonViewNumber;
- (id)initWithFrame:(CGRect)frame
title:(NSString *)title
tag:(int)tag
{
self = [super initWithFrame:frame];
if (self) {
[self setTitle:title forState:UIControlStateNormal];
[self setTag:tag];
self.titleLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self setBackgroundImage:[[UIImage imageNamed:#"btn_white_add.png"] stretchableImageWithLeftCapWidth:20.0 topCapHeight:0.0] forState:UIControlStateNormal];
[self addTarget:self action:#selector(didSelect) forControlEvents:UIControlEventTouchUpInside];
self.isPressed = NO;
}
return self;
}
#implementation ButtonsView
#synthesize listOfButtons;
- (id)initWithFrame:(CGRect)frame bundle:(NSArray *)data
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
listOfNames = [[NSArray arrayWithArray:data] retain];
listOfButtons = [[NSMutableArray alloc] init];
currentViewNumber = 0;
viewNumber = 0;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGSize maximumLabelSize = CGSizeMake(300,24);
UIFont *buttonFont = [UIFont fontWithName:#"Helvetica" size:14.0];
float lineSize = 0;
float lineNumber = 0;
NSArray *listOfFrameX = [NSArray arrayWithObjects:
[NSString stringWithFormat:#"%d",FIRST_LINE_Y],
[NSString stringWithFormat:#"%d",SECOND_LINE_Y],
[NSString stringWithFormat:#"%d",THIRD_LINE_Y],
nil];
for (int i = 0; i < [listOfNames count]; i++) {
CGSize expectedLabelSize = [[[listOfNames objectAtIndex:i] objectForKey:#"name"] sizeWithFont:buttonFont
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeTailTruncation];
if ((lineSize + expectedLabelSize.width) > 260) {
lineNumber++;
lineSize = 0;
}
if (lineNumber > 2) {
viewNumber ++;
lineSize = 0;
lineNumber = 0;
}
CGRect newFrame = CGRectMake(lineSize,
[[listOfFrameX objectAtIndex:lineNumber] floatValue],
expectedLabelSize.width+30,
24);
CustomButton *myButton = [[CustomButton alloc] initWithFrame:newFrame
title:[[listOfNames objectAtIndex:i] objectForKey:#"name"]
tag:[[[listOfNames objectAtIndex:i] objectForKey:#"id"] intValue]];
myButton.buttonViewNumber = viewNumber;
[listOfButtons addObject:myButton];
if (viewNumber == 0) {
[self addSubview:myButton];
}
lineSize += expectedLabelSize.width + 40;
[myButton release];
}
}
this way it works:
- (void)viewDidLoad
{
[super viewDidLoad];
placeholders = [[NSArray arrayWithObjects:
something,something, something,something,nil] retain];
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:placeholders];
[self.view addSubview:buttonsView];
and like this is doesnt work:
- (void)getCompanyNames:(id)result
{
NSArray *listOfCompanies = (NSArray *)result;
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:listOfCompanies];
[self.view addSubview:buttonsView];
}
i need to add the "buttonsView" object to self.view after the -viewDidLoad
drawRect: isn't exactly the place you should be creating subviews (Buttons are subviews) for your view. This should either go into initWithFrame: or awakeFromNib, depending on your view creation method: programmatically or using a nib.

UIButton failed to call functions?

I have a viewcontroller(mainViewController) and view class(UIView class, mainView). mainViewController, I called a method "generateView" from mainView class. Here is the code:
Method 1:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
Method 2:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:mainViewController action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
What I really need is method 2, cuz I want to call the updateData in mainViewController, but no matter how i tried, the button is not calling the function thats supposed to be called. Any idea?
EDIT:
This is how I called the view class
- (void) loadContent: (id) sender {
[self removeSubmenus];
switch ([sender tag]) {
case 2001:
{
MainView *mainView = [[MainView alloc] initWithSubmenu:CGRectMake(420, 85, 0, 0)];
[self.view addSubview:mainView];
break;
}
default:
break;
}
}
You should set delaysContentTouches to YES on the UIScrollView.
You're also leaking a bunch of memory. Make sure you're releasing both the UIButton (b) and NSData (imageData) objects as soon as you're done with them.
--
EDIT: I tried your code and it works fine. But it seems you wanted all this code in a UIView, so I threw together a quick sample.
TestView.h
#import <UIKit/UIKit.h>
#interface TestView : UIView {}
#end
TestView.m
#import "TestView.h"
#implementation TestView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIScrollView *container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:b];
[b release];
col++;
}
[self addSubview:container];
}
return self;
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
- (void)dealloc {
[super dealloc];
}
#end
TestController.h
#interface TestController : UIViewController { }
#end
TestController.m:
#import "TestController.h"
#import "TestView.h"
#implementation TestController
- (void) generateView {
TestView *tv = [[TestView alloc]initWithFrame:[self.view frame]];
[self.view addSubview:tv];
[tv release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self generateView];
}
- (void)dealloc {
[super dealloc];
}
#end
Try adding this code to your method
container.delaysContentTouches = NO;
container.canCancelContentTouches = NO;
Pls modify your code to avoid memory leaks. Make sure you delete objects that you take ownership of.
Try this,
[b addTarget:mainViewController.view action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];

Thumbnail grid of images

How does one create a dynamic thumbnail grid?
How is a grid created with thumbnails of images like the photo app on iphone?
How are these spaces arranged dynamically? e.g. adding and removing thumbnails.
this is my simple grid view app
- (void)viewDidAppear:(BOOL)animated {
[[Grid_ViewAppDelegate sharedAppDelegate] hideLoadingView];
temp = temp+1;
if (temp ==1){
NSLog(#"temp:%d",temp);
int n = 20; //Numbers of array;
NSArray *t = [[NSArray alloc] initWithObjects:#"calpie.gif",#"chrysler_electric.png",#"chrysler_fiat_cap.gif",#"cleanup.gif",#"ecylindri.gif",#"elect08.png",#"globe.gif",#"heat.gif",#"insur.gif"
,#"jobs.gif",#"office.gif",#"opec1.gif",#"orng_cap.gif",#"poll.gif",#"pollen.gif",#"purbar.gif",#"robinson.gif",#"robslink_cap.gif",#"scot_cap.gif",#"shoes.gif",nil];
myScrollView.contentSize = CGSizeMake(320, 460+n*2);
myScrollView.maximumZoomScale = 4.0;
myScrollView.minimumZoomScale = 1;
myScrollView.clipsToBounds = YES;
myScrollView.delegate = self;
NSString *mxiURL = #"http://meta-x.com/biflash/images/";
int i =0,i1=0;
while(i<n){
int yy = 4 +i1*79;
for(int j=0; j<4;j++){
if (i>=n) break;
CGRect rect;
rect = CGRectMake(4+79*j, yy, 75, 75);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
NSString *nn = [mxiURL stringByAppendingString:[t objectAtIndex:i]];
UIImage *buttonImageNormal=[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: nn]]];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
button.tag =i;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside ];
//[self.view addSubview:button];
[myScrollView addSubview:button];
//[buttonImageNormal release];
[button release];
i++;
//
}
i1 = i1+1;
//i=i+4;
}
}
}
in AppDelegate
+ (Grid_ViewAppDelegate *)sharedAppDelegate
{
return (Grid_ViewAppDelegate *)[UIApplication sharedApplication].delegate;
}
- (void)showLoadingView
{
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor grayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(142.0, 222.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
CGRect label = CGRectMake(142.0f, 255.0f, 71.0f, 20.0f);
lblLoading = [[UILabel alloc] initWithFrame:label];
lblLoading.textColor = [UIColor whiteColor];
lblLoading.font = [UIFont boldSystemFontOfSize:14];
// UILabel
lblLoading.backgroundColor =[UIColor clearColor];
[lblLoading setText:#"Loading..."];
//[lblLoading setTextAlignment:UITextAlignmentCenter];
[loadingView addSubview:lblLoading];
}
[window addSubview:loadingView];
}
- (void)hideLoadingView
{
[loadingView removeFromSuperview];
}
definitely if u apply this logic. u get succeed