iOS: How to copy contents from a scrollview into another scrollview - ios

Am created UIScrollView programatically and added multiple buttons into that.
Its working well without any prob.
But i need to create another scrollview by copying contents from previous scrollview.
Query:
How to copy First_Scrollview content into Second_Scrollview
Code:
- (void)ScrollviewItems
{
int x = 5;
int y = 5;
for(int i=0; i<totalButtonsCount; i++)
{
CategoryItem = [[UIButton alloc]initWithFrame:CGRectMake(x, y, buttonWidth, 50)];
CategoryItem.titleLabel.backgroundColor = [UIColor clearColor];
CategoryItem.backgroundColor = [UIColor redColor];
[CategoryItem setTitle:[NSString stringWithFormat:#"%d",i]
forState:UIControlStateNormal];
CategoryItem.tag = i;
[CategoryItem addTarget:self
action:#selector(CategoryItemAction:)
forControlEvents:UIControlEventTouchUpInside];
[First_Scrollview addSubview:CategoryItem];
x = x + (buttonWidth + 5);
}
First_Scrollview.contentSize = CGSizeMake(x,50);
Second_Scrollview = [self.Category_Scrollview copy]; // Error
}
Error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIScrollView copyWithZone:]: unrecognized selector sent to instance

you can do this by this for loop also
for(UIView *v in self.scrollview1.subviews){
[self.scrollview2 addSubview:v];
}

You can't copy views in the way you are trying.
You need to do it as :
NSData * viewData = [NSKeyedArchiver archivedDataWithRootObject:myView];
NSView * viewCopy = [NSKeyedUnarchiver unarchiveObjectWithData:viewData];

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;

How to set UIPageControl with image in iOS8 Objective c?

I want to set UIPageControl with images in the place of dots. I implemented the following code but it always crashing.Please help me.
-(void)updateDots
{
for (int i=0; i<[_pageControl.subviews count]; i++) {
UIImageView *dot = [_pageControl.subviews objectAtIndex:i];
if (i==_pageControl.currentPage)
dot.image = [UIImage imageNamed:#"on.png"];
else
dot.image = [UIImage imageNamed:#"off.png"];
}
}
In iOS8,i got the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setImage:]:
unrecognized selector sent to instance 0x7f9dd9eaabb0'
You shouldn't assume that the UIPageControl will contain UIImageViews (it doesn't).
Here's how to do this with public APIs:
- (void)updateDots
{
// this only needs to be done one time
// 7x7 image (#1x)
_pageControl.currentPageIndicatorTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"on.png"]];
_pageControl.pageIndicatorTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"off.png"]];
}
you are getting UIView in for loop. check if dot is UIImageView Class then set image.
id object = [_pageControl.subviews objectAtIndex:i];
if([object isKindOfClass:[UIImageView Class]])
{
UIImageView *dot = (UIImageView *)object;
if (i==_pageControl.currentPage)
dot.image = [UIImage imageNamed:#"on.png"];
else
dot.image = [UIImage imageNamed:#"off.png"];
}
Hope it will help you.
Remember, subviews don't always have to be UIImageViews. For example, UITableViewCells often have enclosing views or so within them. You need to make the change below.
-(void)updateDots
{
for (int i=0; i<[_pageControl.subviews count]; i++) {
if ([[_pageControl.subviews objectAtIndex:i] isKindOfClass:[UIImageView Class]])
{
UIImageView *dot = (UIImageView *)[_pageControl.subviews objectAtIndex:i];
if (i==_pageControl.currentPage)
dot.image = [UIImage imageNamed:#"on.png"];
else
dot.image = [UIImage imageNamed:#"off.png"];
}
}
}
I've noticed that in a UITableViewCell, there is always an enclosing UIView for the cell content. You need to recursively go into this view to find the UIImageView you are looking for.

finding exception "unrecognized selector sent to instance" only occurs in iOS6

I am getting an exception in my iPhone-app,
-[__NSCFString sizeWithAttributes:]: unrecognized selector sent to instance,
when I start my app uner iOS6.1, under iOS7 or higher everything is OK.
The only difference between iOS6 and higher in my project are the XIBs. The error occurs when I press a button.
Maybe it comes from the different XIB, maybe not.
It looks like a memory leak, but i cant figure out why it happens.
The Exception occurrs when is try to calculate the size of a text from a button.
I set Exception-breakpoints to find the error.
Here some infos from the stacktrace:
In this method the error occurs:
- (float) calculateButtonWidth:(TypeButtonRest*) typeButtonRest{
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *userAttributes = #{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor blackColor]};
const CGSize textSize = [[typeButtonRest text] sizeWithAttributes: userAttributes];
...
The method is called from here:
- (ButtonMatrixInfos*) calculateButtonSchema:(NSMutableArray*) buttons screenWidth:(double)screenWidth minMargin:(double)minMargin{
ButtonMatrixInfos *returnValue = [[[ButtonMatrixInfos class] alloc] init];
int buttonCount = [buttons count];
[buttons retain];
for (int i=0; i < buttonCount; i++) {
float curWidth = [self calculateButtonWidth:[buttons objectAtIndex:i]];
maxButtonWidth = curWidth > maxButtonWidth ? curWidth : maxButtonWidth;
}
...
My assumption is, that buttons is corrupted. They are coming from here:
-(RadioButtonContainer*)addRadioButtons:(NSMutableArray *)buttons withButtonGroupName:(NSString*) groupName andMarginLeft:(int) marginLeft andMarginRight:(int) marginRight preselected:(NSString*) preselected {
ButtonListLayouter *bll = [[[[ButtonListLayouter class] alloc] init]retain];
ButtonMatrixInfos *bmi = [bll calculateButtonSchema:buttons screenWidth:(screenSize.width - marginLeft - marginRight) minMargin:5];
...
Created here:
NSMutableArray *buttonsRest = [[[NSMutableArray alloc] init]retain];
for (int i=0; i < [buttons count]; i++) {
TypeButtonRest *tpr = [[[[TypeButtonRest class] alloc] init]retain];
tpr.text = [[buttons objectAtIndex:i] objectForKey:#"value"];
tpr.key = [[buttons objectAtIndex:i] objectForKey:#"key"];
[buttonsRest addObject:tpr];
}
I hope this codefragments can help.
best regards
sizeWithAttributes is only available starting at iOS 7.0. You want to use sizeWithFont in iOS 6. Read more here

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray length]: unrecognized selector sent to instance

Ok so I've written an algorithm here that seems to not work. Basically it draws a list of buttons across multiple pages. It's adapted so that 4 buttons will be drawn per page on iPhone 5, and 3 on iPhone 4S and earlier.
But for some reason, in the 'setFrame' method, I get this error:
Terminating app due to uncaught exception :
'NSInvalidArgumentException', reason: '-[__NSCFArray length]: unrecognized selector sent to instance
The weird thing is that nowhere in the algorithm, or anywhere else in the app does the method length]; get called.
Please also note that I do no when to use this method, and I also know that NSArrays don't have any method length.
Here's the algorithm:
// creates the chapters
+(void)createChapterInScrollView:(UIScrollView *)scrollview withArray:(NSArray *)array withTarget:(id)target andMethod:(SEL)method
{
// sets up some initial variable
int x = 20;
int y = 40;
// fills an array with the y values
int yValues;
NSMutableArray *yContainer = [[NSMutableArray alloc] init];
if (screenHeight == 568) {
yValues = 4;
} else {
yValues = 3;
}
for (yValues = yValues; yValues > 0; yValues = yValues - 1) {
[yContainer addObject:[NSString stringWithFormat:#"%i", y]];
y = y + 70;
}
// creates the buttons using the number of pages
int numOfpages = [self numOfPagesFromArray:array];
int numofPagesLeft = [self numOfPagesFromArray:array];
int numOfButtonsLeft = [array count];
int currentButton = 0;
if (numofPagesLeft == 0) {
} else {
for (numofPagesLeft = numofPagesLeft; numofPagesLeft >= 0; numofPagesLeft = numofPagesLeft - 1) {
for (id object in yContainer) {
if (numOfButtonsLeft > 0) {
UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
[newButton setTitle:[array objectAtIndex:currentButton] forState:UIControlStateNormal];
[newButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[newButton setFrame:CGRectMake(x, [object floatValue], 280, 50)];
[newButton setTag:(currentButton+1)];
[newButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[newButton.titleLabel setTextAlignment:NSTextAlignmentLeft];
[newButton addTarget:target action:method forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:newButton];
numOfButtonsLeft = numOfButtonsLeft - 1;
currentButton ++;
}
}
x = x + 320;
}
}
// checks if any buttons were actually created
if (numOfpages == 0) {
// tells the user that no content has been downloaded
UILabel *errorLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 216)];
[errorLabel setBackgroundColor:[UIColor clearColor]];
[errorLabel setTextColor:[UIColor whiteColor]];
[errorLabel setNumberOfLines:10];
[errorLabel setFont:[UIFont systemFontOfSize:17]];
[errorLabel setTextAlignment:NSTextAlignmentCenter];
[errorLabel setText:#"Oops!\n\nLooks like no readable content has been downloaded!\n\nThe content will be automatically downloaded right now!"];
[scrollview addSubview:errorLabel];
}
}
Thanks guys!
In Xcode, go to the Breakpoints navigator, and add exception breakpoint. Simple description how to do it is in this SO answer
Once you have this, you should see exactly which line of code causes the exception.

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