Showing Selected Buttons if Back button is Pressed [closed] - ios

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
On first Page i am having some buttons , if i press any button it will move to Second page , here if i press back button in the navigation bar it will move to first page
i have created the buttons dynamically based on the array count ,i want to show the selected button when i move back to first page , how can i do this ?Please help me to do this .here is the code that i have used for creating buttons
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
//
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton * word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}

=====Appdelegate.h========
#property (assign, nonatomic) long int btnTag;
=======CategoryViewController.h============
import "AppDelegate.h"
#interface CategoryViewController : UIViewController
{
AppDelegate *appdel;
}
===========CategoryViewController.m=======
add code
if(appdel.btnTag == word.tag)
{
word.selected = YES;
}
below [word setTag:i]; code
then add
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
in - (IBAction)btn1Tapped:(id)sender method

The UIButton object has different states included the "Selected state". You can set different background image or title for each state you want. When you press it you can change its state like this:
//After you inited your UIButton Object do this:
[button setBackgroundImage:selectedBGImage forState:UIControlStateSelected];
[button setBackgroundImage:deselectedBGImage forState:UIControlStateNormal];
//You can also find the title change method for state accordingly
- (void)buttonAction:(UIButton *)sender
{
sender.selected = !sender.selected;
//TODO
}
So, when you pop back, the button will keep its "selected" state.

You have to store button tag in appdelegate and while creating button check with button tag/i values and do selected. please see below code
in AppDelegate.h
#property (assign, nonatomic) int btnTag;
create an object of AppDelegate on your current ViewController then
AppDelegate *appdel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
int buttonheight = 30;
.
.
.
[word setTag:i];
if(word.tag == appdel.btnTag)//appdel is object of AppDelegate
{
word.selected = YES;
}
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}
enter image description here
I am getting like below screenshot , if i tapped any button it will move to next page and the backgroundcolor is changed to red color,and come back to same page by clicking back and now i tapped another button it is also showing in red color.
I have use this two lines in button action method :
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];

Related

Getting TextField Text On Button Click

I am developing an IOS App. I am creating a text field and a button dynamically, and I want to get textfield's text on button click, but I'm getting an error:
[UIView setText:]: unrecognized selector sent to instance
Here is my code:
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
UITextField *copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
[copyfield setDelegate:self];
[copyfield setTag:i];
[_filterPossibleValueView addSubview:copyfield];
x = x+_field.frame.size.height+10;
UIButton *copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
[copyAddButton setTag:i];
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
// [_addfieldArray removeObjectAtIndex:index];
UITextField *field = [_filterPossibleValueView viewWithTag:index];
NSString *myText = field.text;
}
The default value for the tag property is 0, and you are setting that value to one of the text fields. So, when you try to get the view with tag == 0, it will have more than one view with that tag.
You should use an offset when setting the tag:
[copyfield setTag:kOffset + i];
...
[copyAddButton setTag:kOffset*2 + i]; // note that the button and the text field should not have the same tag either
where kOffset is defined (for example) like this:
let kOffset: Int = 1000
Then, to get the text field's text, you can use:
NSInteger tag = button.tag - kOffset;
UITextField *field = [_filterPossibleValueView viewWithTag:tag];
NSString *myText = field.text;

click button action in sequentially order in UITableView

created 4x4 metrics button in UITableView.
I want to select the button in sequentially order.
// button Creation in cell for row Index
for (int i = 0; i< [buttonArray count]; i++)
{
int buttonSpace = 10 * i + 10;
NSLog(#"ButtonPosition:%d",buttonSpace + (i * 50));
cell.Button = [[CustomButton alloc] initWithFrame:CGRectMake(buttonSpace + (i * 50),35, 50, 50)];
cell.Button.layer.cornerRadius = 25;
[cell.Button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
cell.Button.buttonIndex = i;
[cell.ScrollView addSubview:cell.Button];
cell.ScrollView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.3];
}
rowIndexValue = indexPath.row;
// Button action in view controller.
-(void)buttonAction:(CustomButton *)sender
{
if (rowIndexValue) {
int counter = (int)[sender buttonIndex];
if (counter == incrementValue)
{
sender.backgroundColor = [UIColor redColor];
counter += 1;
incrementValue = counter;
}
else{
sender.selected = NO;
}
}
}
The order of button action in sequential order, for any random row's.
user select 3rd row but selection row in third row start from 1st button then 2nd button then 3rd button finally 4th button.
4x4 - > 4 row for UITableview 4 button in each row. Once button is click it will be in disable Mode
Set proper value so that you can recognise button column as well as row position. buttonIndex is just saving i value so you will only get column position.You may set button.tag=indexPath.row and use it in the buttonAction method to know the row position.
Declare NSInteger tagValue globally in your viewController.
-(NSUInteger)getRowByBtn:(UIButton *)btn :(UITableView *)tblView
{
CGPoint center= btn.center;
CGPoint rootViewPoint = [btn.superview convertPoint:center toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:rootViewPoint];
NSLog(#"indexPath = %ld", (long)indexPath.row);
return indexPath.row;
}
With the help of above method you can get indexpath.row value from which you can determine the button for each row in the tableview.
[cell.Button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
-(void)buttonAction:(UIButton*)sender
{
UIButton *btn=(UIButton *)sender;
tagValue = [self getRowByBtn:btn :yourTableview];
[[self.view viewWithTag:tagValue]setUserInteractionEnabled:YES];
//or any other action
}
Set UIButton tag in CellForRowAtIndexPath
Like this :
[cell.btn_name addTarget:self action:#selector(onclick_button:) forControlEvents:UIControlEventTouchUpInside];
self.btn_name.tag=indexpath.row;
And
-(IBAction)onclick_button:(id)sender
{
int btn_index= ((UIView*)sender).tag;
NSLog(#"Btn index:%d",btn_index);
}
It fix the problem with below code.
-(void)buttonAction:(UIButton*)sender{
CGPoint center = sender.center;
CGPoint rootViewPoint = [sender.superview convertPoint:centre toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
sender.userInteractionEnabled = NO;
sender.backgroundColor = [UIColor redColor];
CustomButton *enableNextButton = (CustomButton *) [[self.goalsTableView cellForRowAtIndexPath:indexPath] viewWithTag:sender.tag+1];
enableNextButton.userInteractionEnabled = YES;
}

How to pass a UIButton's frame and origin between ViewControllers

I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:#"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:#"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:#"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:#"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? #"calendarFlyout_dayContainer_insideMonth.png"
: #"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:#selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:#selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
I want to get the frame of button and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated.
Use the transform feature.
// animate in year calendar
_yearCalendarView.hidden = NO;
self.curMonthView.monthLabel.hidden = YES;
CalendarMonthView *monthView = [CalendarMonthView new];
monthView.delegate = self;
CGRect buttonFrame = _currentDayButtonFrame;
_yearCalendarView.frame = CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y + buttonFrame.size.height, buttonFrame.size.width, buttonFrame.size.height);
NSLog(#"_yearCalendarView frame: %#", NSStringFromCGRect(_yearCalendarView.frame));
_yearCalendarView.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:kAnimation_ExpandCalendarDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
_yearCalendarView.transform = CGAffineTransformIdentity;
_yearCalendarView.frame = CGRectMake(_monthSwiperScrollView.frame.origin.x, _monthBarImageView.frame.size.height + 20, _monthSwiperScrollView.frame.size.width + 2, _yearFlyoutHeight);
} completion:^(BOOL finished) {
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector (yearCalendarAnimationDidStop:finished:context:)];
}];
If you are making a segue from the CalendarMonthView to the CalendarFlyoutView then you can just add this method to the CalendarMonthView.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
CalendarFlyoutView * view = segue.destinationViewController;
view.buttonFrame = button.frame;
}
and in your CalendarFlyoutView.h
#interface CalendarFlyoutView : UIViewController
#property CGRect buttonFrame;
#end
A couple of questions that need to be answered to best help you:
1) Are CalendarMonthView and CalendarFlyoutView UIView or UIViewController? You say view controller, but the class name says otherwise.
2) What is happening in the method 'dayButtonTapped'? Are you performing a segue there? Are you somehow creating or loading an instance of CalendarFlyoutView?
3) If you are not using a segue, are you somehow creating and add a child view controller for CalendarFlyoutView to CalendarMonthView?
4) What is the desired transition (your animation)? Does the CalendarFlyoutView start at the same size as the button, then fill the whole screen?
5) Is there a specific reason that you are setting the button's frame instead of constraining it in the correct place?
Once we know a little more about these questions we should be able to provide some more concrete suggestions.
It's still not very clear where the actual animation code is being run. In your question, you state "I want to get the frame of button and use it in this animation used in CalendarFlyoutView.m." which seems to imply the animation code is in CalendarFlyoutView, which seems like an odd place for it.
There are a few things I could recommend, given my incomplete understanding of the whole of the code:
1) Move the animation code to the dayButtonTapped method, where you already have a reference to the button, and therefore it's frame. It also seems like a more logical place for it.
2) Where ever you are instantiating the CalendarFlyoutView (not shown in the code you posted), assign the button frame there.
3) If there is only a single instance of CalendarFlyoutView and you have a reference to it in CalendarMonthView, you could assign a property of the flyout view that is the frame of the button you already have a reference to in the dayButtonTapped method.
I have to add though, that these are just work arounds to what seems like a structural issue. Is this a reusable control you are trying to write? Why did you decide to not use the storyboard or view controllers? Why are you using frames and absolute sizes and positions at all instead of letting auto layout do it's job (you will bang your head against the wall for hours trying to tweak everything to run correctly in all orientations and all possible device screen sizes).

Targeting programmatically created UIButton

Question: How do I target one of many dynamically created UIButtons so I can change its properties?
Background: I have a storyboard with a UIViewConroller. When this UIVC loads a UIScrollView is added, to which a UIImageView is placed that has an exhibition floor plan. Each exhibitor has an entry in a database that contains its location on the floor plan. When the UIVC is loaded a loop is run for all exhibitors and each one has a UIButton drawn on the UIIV. When a UIB is clicked the button background colour is changed (to confirm which exhibitor has been selected) and a UIAlertView is shown with information about that exhibitor. When the UIAV's 'cancel' (ok) button is pressed the UIAV closes and the background highlight colour that was applied previously should be removed but here is where I am having the problem. I am unable to target the UIButton so I can change its background colour.
What I have tried so far: As each button is created I am giving it a tag and a title and recording both in an array. When the 'cancel' button is pressed on the UIAlertView I have tried checking the tag in the array but I still cannot actually target the UIButton.
I was thinking something like this:
// obviously not correct syntax but the kind of thing I want
[exhibitorBtn(tag) setBackgroundColor:[UIColor greenColor]];
So, say I have 12 UIButtons all called exhibitorBtn but with different titles and tags:
Object ----- Name ---------- Title -------- Tag
UIButton -- exhibitorBtn -- Glaxo ------ 1
UIButton -- exhibitorBtn -- Porsche --- 2
UIButton -- exhibitorBtn -- Rolex ------- 3 < How would I target that button's properties?
Edit - added the code that creates the buttons just to clarify:
for (NSDictionary *dict in exhibitorStandArray) {
NSInteger currentPosition = [exhibitorStandArray indexOfObject:dict];
NSLog(#"Position in array = %li", (long)currentPosition);
if (![dict[#"locCoords"] isEqual: #""]) {
NSInteger buttonTag = [exhibitorStandArray indexOfObject:dict];
NSString *standNo = dict[#"locStandNo"];
NSMutableDictionary *buttonDictionary = [[NSMutableDictionary alloc] init];
[buttonDictionary setObject:[NSNumber numberWithInteger:buttonTag] forKey:#"buttonTag"];
[buttonDictionary setObject:standNo forKey:#"buttonStandNo"];
[_masterButtonList addObject:buttonDictionary];
NSString *locCoords = dict[#"locCoords"];
NSArray *tempArray =[locCoords componentsSeparatedByString:#","];
tlcTop = [[tempArray objectAtIndex:0] integerValue];
tlcLeft = [[tempArray objectAtIndex:1] integerValue];
brcTop = [[tempArray objectAtIndex:2] integerValue];
brcRight = [[tempArray objectAtIndex:3] integerValue];
buttonWidth = brcRight - tlcLeft;
buttonHeight = brcTop - tlcTop;
testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
testBtn.frame = CGRectMake(tlcTop, tlcLeft, buttonHeight, buttonWidth);
testBtn.titleLabel.text = standNo;
testBtn.tag = buttonTag;
NSLog(#"UIButton Title = %#", testBtn.titleLabel.text);
NSLog(#"UIButton Tag = %li", (long)testBtn.tag);
testBtn.titleLabel.hidden = YES;
[testBtn addTarget:self action:#selector(displayInfo:) forControlEvents:UIControlEventTouchUpInside];
[_buttonArray addObject:testBtn];
[_imageView addSubview:testBtn];
}
}
Why can't you just use viewWithTag:
UIButton * button = (UIButton *)[self.scrollView viewWithTag:tag];
Your code probably looks something like this:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[scrollView addSubview:exhibitorBtn];
}
Just change the loop so every button will be added to an array, too. Declare a NSMutableArray as a property: #property (strong, nonatomic) NSMutableArray *buttonsArray;
And #synthesize and initialise it in your init method. buttonsArray = [[NSMutableArray alloc] init]
Then, change the loop like I said above:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[buttonsArray addObject:exhibitorBtn];
[scrollView addSubview:exhibitorBtn];
}
Finally, when you want to access the buttons:
for (int i = 0; i < [buttonsArray count]; i++)
{
UIButton *button = [buttonsArray objectAtIndex:i];
if (button.tag == 3) { // This is the button you wanted to target!
[button setHidden:YES];
}
}
Let's make it clear: you did set target and action of UIButton to controller's IBAction method and get the button as sender argument. Now you show UIAlertView and after it is dismissed, you want to send some message to that button, right?
Another method is to set delegate property for UIAlertView and respond to – alertView:clickedButtonAtIndex: delegate method. Trouble is that sender is lost at that point. You may use objc_setAssociatedObject to associate UIButton with UIAlertView and the retrieve it back when delegate method fires:
#import <objc/runtime.h>
static char myButtonKey = 0; // to use address as a key (value is irrelevant)
- (IBAction)buttonDidClick:(id)button
{
UIAlertView *alertView = <setup alert>;
[alertView setDelegate:self];
objc_setAssociatedObject(alertView, &myButtonKey, button, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
<show alert>;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIButton *thatButton = objc_getAssociatedObject(alertView, &myButtonKey);
<use thatButton>;
}
Try to create button in this way and add selector to them :
for (int i = 0; i < 5; i++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
button.tag = i;
[button addTarget:self
action:#selector(buttonPressedMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
// add button to subview here
}
In method, just do whatever, you want to do :
- (void) buttonPressedMethod : (id) sender {
UIButton *selectedButton = (UIButton *)sender;
if (selectedButton.tag == 0) {
}
else if (selectedButton.tag == 1) {
}
else {
}
}

enable pinch to zoom in viewcontroller

I want users to be able to use pinch to zoom in my app which uses Storyboard and programmatically generated buttons and labels to produce a View within a Viewcontroller. In the View's Attribute inspector I have checked both User Interaction Enabled and Multiple Touch. But no pinch to zoom seems to work.
The code which creates the important part of the View is as follows.
- (void)viewDidLoad
{
[super viewDidLoad];
NSInteger xPipsOrigin = 0;
NSInteger xPipsStep = 22.0;
NSString* cards = #"AKQJT98765432";
NSInteger yPipsOrigin = 100;
if (UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){
xPipsOrigin = 0;
xPipsStep = 22.0;
xPipsStep = 34.0;
}
else{
xPipsOrigin = 100;
xPipsStep = 40.0;
}
NSInteger xPipsCurrent = xPipsOrigin;
self.countCards = 0;
self.cardList = [NSMutableArray arrayWithCapacity:0];
yPipsOrigin = 100;
xPipsCurrent = xPipsOrigin;
for( int x=0;x<[cards length]; x++ ){
[cards substringWithRange:NSMakeRange(x,1)];
UIButton *b= [UIButton buttonWithType:UIButtonTypeRoundedRect];
xPipsCurrent += xPipsStep;
[b setTitle:[cards substringWithRange:NSMakeRange(x,1)] forState:UIControlStateNormal];
[b setTitle:#" " forState:UIControlStateDisabled];
[b setFrame:CGRectMake(xPipsCurrent, yPipsOrigin, 20, 20)];
[b setEnabled:YES];
[b setUserInteractionEnabled:YES];
[self.view addSubview:b];
[b addTarget:self action:#selector(spadeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
xPipsCurrent = xPipsOrigin + xPipsStep/2;
for( int x=0;x<[cards length]-1; x++ ){
xPipsCurrent += xPipsStep;
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake( 0, 0, 20, 20)];
lab.text = #"\u2660";
lab.backgroundColor = [UIColor clearColor];
lab.center = CGPointMake(xPipsCurrent+10, yPipsOrigin+10);
[self.view addSubview:lab];
}
}
How can I enable Pinch to Zoom in this app?
If you want to enable pinch to zoom on a UIView you have to wrap it into a UIScrollView first
Whilst you can use User Interaction Enabled and try do it that way, it'll be easier to add a UIGestureRecogniser to your UIView. That way it handles most of the setup code for you, and when it detects a pinch triggers a method.
Basic example in Objective-C:
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handlePinchGesture:)];
[self.view addGestureRecognizer:pinchGesture];
- (void)handlePinchGesture:(id)sender
{
NSLog(#"Recieved pinch");
UIPinchGestureRecognizer *senderGR = (UIPinchGestureRecognizer *)sender;
NSLog(#"Scale is: %f", senderGR.scale);
}
And in Swift:
let pinchGestureRecognizer = UIPinchGestureRecognizer.init(target: self, action: #selector(ViewController.handlePinchGesture(_:)))
self.view.addGestureRecognizer(pinchGestureRecognizer)
func handlePinchGesture(sender:AnyObject) {
print("Received pinch")
let senderGR = sender as! UIPinchGestureRecognizer
print("Scale is \(senderGR.scale)")
}

Resources