UIButton addTarget does not work in subclass of UIViewController - ios

This is MyViewController.m
actionNames[0] = #"hoge";
actionNames[1] = #"piyo";
NSMutableArray *actionConts = [[NSMutableArray alloc] init];
for(int i=0; i<[actionNames count]; i++){
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(DEVICE_WIDTH/3 * i, 0, DEVICE_WIDTH/3, 45)];
// actionNames is NSMutableArray
[btn setTitle:actionNames[i] forState:UIControlStateNormal];
[btn setUserInteractionEnabled:YES];
actionConts[i] = btn;
}
// ↓ does not work
[actionConts[1] addTarget:self action:#selector(follow) forControlEvents:UIControlEventTouchUpInside];
// actionSubs is NSMutableArray
for(int i=0; i<[actionConts count]/3; i++){
actionSubs[i] = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 45)];;
}
for(int i=0; i<[actionConts count]; i++){
int sub = floor( (float)i / 3.0 );
[actionSubs[sub] addSubview:actionConts[i]];
}
UIScrollView *actionScr = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 150, 320, 45)];
[actionScr setPagingEnabled:YES];
[actionScr setShowsHorizontalScrollIndicator:NO];
[actionScr setBounces:NO];
actionScr.contentSize = CGSizeMake([actionSubs count] * DEVICE_WIDTH, 45);
for(int i=0; i<[actionSubs count]; i++){
[actionScr addSubview:actionSubs[i]];
}
Create a button. => actionConts[n]
addTarget to actionConts[1]
actionSubs[] alloc
addSubView actionConts[n] to actionSubs[n]
addSubView actionSubs[n] to actionScr
(addSubView actionScr to drw)
(drw is a UIView instance. "IBOutlet UIView *drw;")
When I click this button, It does not work... (´;ω;`)
Please help me.
Thanks.

Your code works fine to me. I only replaced some lines:
[actionConts[1] addTarget:self action:#selector(follow) forControlEvents:UIControlEventTouchUpInside];
replaced with:
for (UIButton *button in actionConts) {
[button addTarget:self action:#selector(follow) forControlEvents:UIControlEventTouchUpInside];
}
that allows adding the actions to each button from array.
Also I replaced for-loop condition from:
for(int i=0; i<[actionConts count]/3; i++)
to:
for(int i=0; i<ceil((float)[actionConts count]/3.0); i++)
that allows having at least one superview for buttons.
Now follow is a method that will fire for each your button. You can set UIButton.tag property to clarify which one is pressed.

Related

How to ADD label inside infinite button?

This is my code:
-(void)scrollView
{
NSInteger buttonCount = 0;
NSInteger buttonSize = 0;
int divisible= 0;
buttonCount=[[arrFullSubCategory valueForKey:#"name"]count];
if(buttonCount==2)
{
divisible = 2;
buttonSize=self.view.frame.size.width/divisible;
}
else
{
divisible = 3;
buttonSize=self.view.frame.size.width/divisible;
}
[viewBtnScroll addSubview:self.scrollViewBtn];
for(int i=0;i<buttonCount;i++)
{
self.scrollViewBtn.scrollsToTop=YES;
self.scrollViewBtn.directionalLockEnabled=YES;
self.automaticallyAdjustsScrollViewInsets = NO;
UIButton *btn;
btn=[[UIButton alloc]initWithFrame:CGRectMake(buttonSize*i,0,buttonSize,self.scrollViewBtn.frame.size.height)];
[btn setTitle:[NSString stringWithFormat:#"%#",[[arrFullSubCategory objectAtIndex:i] valueForKey:#"name"]] forState:UIControlStateNormal];
btn.userInteractionEnabled=YES;
NSInteger tag=[[[arrFullSubCategory valueForKey:#"category"] objectAtIndex:i] integerValue];
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:tag];
highLight=[[UILabel alloc]initWithFrame:CGRectMake(buttonSize*i,10,btn.frame.size.width,20)];
highLight.backgroundColor=[UIColor greenColor];
highLight.hidden=YES;
[btn addSubview:highLight];
[self.scrollViewBtn addSubview:btn];
length = [[arrFullSubCategory valueForKey:#"name"] count];
}
self.scrollViewBtn.contentSize=CGSizeMake(buttonSize*buttonCount, self.scrollViewBtn.frame.size.height);
}
1.That button depend up on the coming json values.
2.That button size is calculated for the screen size.
3.i have created label as globally for some reason,and added that to subview of button ,initially it is hide ,when the button pressed that particular button label hidden=NO;
4.everything i have done perfectly,but my problem is How to give x.origin for the particular label?
5.From my code the label present only at end of the button not for all.
6.If i set x.origin as 0 then its present only at the initial button[first button].
7.That button present in scrollview .....
Simplest solution for this would be
create new UIView (lets name it MyView) of the size you want.
create UILabel of size you want and x and y with respect to MyView
and add it to MyView
Add MyView to your UIScrollView.
Then create a UIButton of the same dimensions as MyView and add it to you same UIScrollView
Important here is you add button to your UIScrollView and not MyView
and you are good to go .. hope this helps...
======= EDITS ======== Use the code as you need
float width = GridScrollView.frame.size.width;
int i,k=0;
for ( i= 0; i < imageArray.count; i+=4) {
for (int j =0; j<4; j++) {
if (i+j <nameArray.count) {
NSLog(#"i = %d j = %d k = %d",i,j,k);
UIActivityIndicatorView *spinner2 = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
[spinner2 startAnimating];
[GridScrollView addSubview:spinner2];
UIView *gridBox = [[UIView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
// gridBox.backgroundColor=[UIColor whiteColor];
[GridScrollView addSubview:gridBox];
UIView *labelBack = [[UIView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/16)];
labelBack.backgroundColor=[UIColor blackColor];
labelBack.alpha=0.5;
[GridScrollView addSubview:labelBack];
UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/16)];
nameLabel.text=nameArray[i+j];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.textColor=[UIColor whiteColor];
nameLabel.font=[UIFont fontWithName:#"Arial" size:12];
[GridScrollView addSubview:nameLabel];
UIButton *gridButton = [[UIButton alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
[gridButton addTarget:self action:#selector(gridButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
gridButton.tag=i+j;
[GridScrollView addSubview:gridButton];
}
} k++;
}
[GridScrollView setContentSize:CGSizeMake(width, (width/4)*(i/4))];
[self.view addSubview:GridScrollView];

Load url selected object in UIWebView (iOS)

I want to open a UIWebView with a url based on the index of a custom object from an array. When I tap a button, based upon the index of objects in an array, I need for the UIWebView to open up that particular url. The problem is that when I open the webview, it will only load the url of the first object (at index 0) in the array. Here is my code:
.m:
//Here's a snippet of my viewDidLoad method.
-(void)viewDidLoad{
[super viewDidLoad];
buyButton = [[UIButton alloc]init];
buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
buyButton.frame = CGRectMake(228, 8, 25, 25);
[buyButton setBackgroundImage:[UIImage imageNamed:#"buy-now.png"] forState:UIControlStateNormal];
[buyButton addTarget:self action:#selector(buyBttnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buyButton];
int count = [self->myArray count];
for (int index = 0; index < count; index++)
{
DomainModel *eachObject = [self->myArray objectAtIndex:buyButton.tag];
buyButton.tag = index;
urlString = [NSString stringWithFormat:#"%#",eachObject.url];
NSLog(#"Selected index: %d",urlString);
}
-(void)buyBttnPressed:(id)sender{
UIWebView *buyView = [[UIWebView alloc] initWithFrame:CGRectMake(9,132,305,368)];
buyView.backgroundColor = [UIColor whiteColor];
buyView.scalesPageToFit = YES;
buyView.delegate = self;
[self.view addSubview:buyView];
UIButton *cancelBttn = [[UIButton alloc]init];
cancelBttn = [UIButton buttonWithType:UIButtonTypeCustom];
cancelBttn.frame = CGRectMake(3, 5, 25, 25);
[cancelBttn setBackgroundImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[buyView addSubview:cancelBttn];
[buyView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
}
How do I fix the loop so that when the buyBttn is pressed, the the url associated with the associated index loads?
it seems that if you call this code on buyBtnPressed, then the TAG of the button will be set to the self.myArray.count -1 always (you're looping but setting it always on the same button).
so current will always point to the same item - the last one in the list.
i think this:
int i = 0;
for (MyObject *obj in self->myArray)
{
i++;
btn.tag = i;
}
should be done on viewDidLoad, or wherever you fill your array in.

get tag of UIButton and those with smaller tags

I'm not understanding if what I'm trying to do is possible or not.
I am creating buttons in for loop:
CGRect rect2 = CGRectMake(50, 230, 40, 40);
for (int i = 0; i<5; i++) {
NSString *stringI = [NSString stringWithFormat:#"%d",i+1];
NSString *stringItouch = [NSString stringWithFormat:#"%dselected",i+1];
UIButton *button = [[UIButton alloc] init];
[button setBackgroundImage:[UIImage imageNamed:stringI] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:stringItouch] forState:UIControlStateSelected];
[button addTarget:self action:#selector(touchButton:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i+1;
button.frame = rect2;
rect2.origin.x = rect2.origin.x + 45;
[scrollView addSubview:button];
}
and after in method touchButton i get the tag of touched button
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
}
}
in the last loop i want to select the buttons that have the tag less than that touched (in this case 3,2,1)
is it possible or not???
thanks everybody
All you need is viewWithTag: like so:
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
/* Add this line */
UIButton *tempButton = (UIButton *)[scrollView viewWithTag:i];
}
}

how to get button title using for loop

//here take a array with letters
_englishArray = [[NSMutableArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
int i=0;
float x=5,y=13;
//add array elements as button title
for (i=0; i< [_englishArray count]; i++) {
button.tag=i+1;
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[_englishArray objectAtIndex:i] forState:UIControlStateNormal];
button.frame= CGRectMake(x, y, 29, 30);
button.titleLabel.textColor =[UIColor whiteColor];
x= x+31;
if (x==320 || x>310) {
x=5;
y=y+40;
}
[_keyboardImageView addSubview:button];
}
// and i add the each button to _keyboardImageView and set title as _english arry elements ...and the get buttons curren title for this code...
//here get the button title useing for loop
for (int j=0;j<=[_englishArray count]; j++) {
// here get button from image view by useing tag
butt = (UIButton *)[_keyboardImageView viewWithTag:j+1];
NSLog(#"%#",butt.titleLabel.text);
}
it prints null not give button title............
Note:i am using button.currentitle also
how is it possible..why its displays null?
Since you set the title with setTitle:forState:, use titleForState: to get the title:
NSLog(#"title is %#", [butt titleForState:UIControlStateNormal]);
Of course this assumes that butt isn't nil. You need to assign the button's tag after you allocate the button:
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag=i+1;
Make sure you define your button in for loop like
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
and than specify tag.
button.tag=i+1;
You have to define button in for loop instead of .h file.
And for get title text
for (int j=0;j<=[_englishArray count]; j++) {
UIButton *butt = (UIButton *)[_keyboardImageView viewWithTag:j+1];
NSLog(#"%#",butt.titleLabel.text);
}
hope it will help you.
_englishArray = [[NSMutableArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
int i=0;
float x=5,y=13;
//add array elements as button title
for (i=0; i< [_englishArray count]; i++) {
button.tag=i+1;
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
button.frame= CGRectMake(x, y, 29, 30);
[button setBackgroundColor:[UIColor grayColor]];
[button setTitle:[_englishArray objectAtIndex:i] forState:UIControlStateNormal];
//button.titleLabel.textColor =[UIColor whiteColor];
[_keyboardImageView addSubview:button];
x= x+31;
if (x==320 || x>310) {
x=5;
y=y+40;
}
}
//here get the button title useing for loop
// and i add the each button to _keyboardImageView and set title as _english arry elements ...and the get buttons curren title for this code....
for (int j=0;j<=[_englishArray count]; j++) {
butt = (UIButton *)[_keyboardImageView viewWithTag:j+1];
NSLog(#"Required Result is %#",butt.titleLabel.text);
}
Try it ,it will work...

UIScrollView with a large number of UIButtons

What I want is a UIView with lots of UIButtons in it. They get placed and arranged according to data stored in an NSArray. Because there are quite a lot of buttons they don't fit on the screen all at once. The user should be able to zoom out to see all the buttons or to zoom in to see details (the label on them) and to easily select them.
I tried two different approaches:
1) I constructed a UIView subclass, put the buttons in it and an instance of this View inside a UIScrollview.
Effect: I can access all Buttons via their tag and scrolling and zooming works fine. BUT I can't get the buttons to handle any events (press on them)...
2) I wrote a UIViewController with exactly the same functionality and added an instance of it to the UIScrollView.
Effect: I can press the buttons now, but scrolling and zooming have stopped to work.
Here the relevant Code of the View:
- (UIView *)initWithArray:(NSArray *)nArray{
self = [super init];
if (self) {
int count = [nArray count];
for (int i=0; i<count; i++) {
UIButton *button = [[UIButton alloc]
initWithFrame:(__some Code to place the Button__);
button.tag = i+1;
NSString *title = [[NSString alloc] initWithFormat:__code for generating Title__];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[self addSubview:button];
}
}
return self;
}
And the Code for the matrixController:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *nArray = [[NSMutableArray alloc] __some code___];
int count = [nArray count];
for (int i=0; i<count; i++) {
UIButton *button = [[UIButton alloc]
initWithFrame:CGRectMake(__some Code to place the Button__];
button.tag = i+1;
NSString *title = [[NSString alloc] initWithFormat:__code for generating Title__];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button];
}
}
And the code for the ScrollViewController:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 768, 970)];
[self.view addSubview:scrollView];
[scrollView setBackgroundColor:[UIColor blackColor]];
//Zooming
[scrollView setMinimumZoomScale:0.25];
[scrollView setMaximumZoomScale:4.0];
[scrollView setDelegate:self];
// constructing the view
[scrollView addSubview:chartView];
[scrollView bringSubviewToFront:chartView];
OR
[scrollView addSubview:[matrixController view]];
How can I get this to work??
I'm able to get a scroll view containing multiple buttons to pan and zoom just fine, with the buttons still handling touch events:
- (void)didTapButton:(UIButton *)button
{
NSLog(#"Button %ld", (long)button.tag);
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scrollView.delegate = self;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3.0f, scrollView.frame.size.height * 3.0f);
scrollView.maximumZoomScale = 3.0f;
UIView *zoomView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, scrollView.contentSize.width, scrollView.contentSize.height)];
zoomView.backgroundColor = [UIColor whiteColor];
for (NSInteger index = 0; index < 100; index++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 50.0f, 10.0f + (50.0f * (CGFloat)index), 100.0f, 30.0f);
button.tag = index;
[button setTitle:[NSString stringWithFormat:#"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
[button addTarget:self action:#selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
[zoomView addSubview:button];
}
[scrollView addSubview:zoomView];
[self.view addSubview:scrollView];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView.subviews objectAtIndex:0];
}
EDIT: I said not to rely on tag in my comment below, yet I'm doing in here. :) It's merely so I could log the button number, so that part should be ignored.
for (int i=0; i<10; i++)
{
UIButton *scrollingbutton_outlet = [[UIButton alloc] init];
scrollingbutton_outlet = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:#"box_normal.png"];
scrollingbutton_outlet.frame = CGRectMake(0, 100, img.size.width, img.size.height);
[scrollingbutton_outlet setTitle:[NSString stringWithFormat:#"%d",i+1] forState: UIControlStateNormal];
scrollingbutton_outlet.tag=i+1;
[buttonArray addObject:[NSString stringWithFormat:#"%d",i+1]];
buttonArray = [[NSMutableArray alloc] init];
[scrollingbutton_outlet setBackgroundImage:img forState:UIControlStateNormal];
[scrollingbutton_outlet addTarget:self
action:#selector(scrollbuttonpress:)
forControlEvents:UIControlEventTouchUpInside];
scrollingbutton_outlet.frame = CGRectMake(img.size.width*i,0, img.size.width, scrollviewoutlet.frame.size.height);
[scrollviewoutlet addSubview:scrollingbutton_outlet];
width = scrollingbutton_outlet.frame.size.width;
height = scrollingbutton_outlet.frame.size.height;
scrollviewoutlet.contentSize = CGSizeMake(width*i+scrollingbutton_outlet.bounds.size.width+5, height);
}

Resources