I want to animate a UIImageView left to right with UIPageControl. I have this code but it seems a bit odd...Specifically because what would I do when I reach image 3? I would have to return and that would mess up the mathematical calculations of the views in the pageControl array the way I have it set up:
-(void)createUIViews{
UIImage *image1 = [UIImage imageNamed:#"GiftCard.png"];
firstView = [[UIImageView alloc] initWithImage:image1];
firstView.backgroundColor = [UIColor grayColor];
firstView.tag = 1;
firstView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
[self.view addSubview:firstView];
CGRect newFrame = firstView.frame;
newFrame.origin.x += 40; // shift right by 50pts
newFrame.origin.y += 40;
[UIView animateWithDuration:1.0
animations:^{
firstView.frame = newFrame;
}];
UIImage *image2 = [UIImage imageNamed:#"MyCard.png"];
secondView = [[UIImageView alloc] initWithImage:image2];
secondView.backgroundColor = [UIColor grayColor];
secondView.tag = 1;
secondView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
UIImage *image3 = [UIImage imageNamed:#"GiftCard.png"];
thirdView = [[UIImageView alloc] initWithImage:image3];
thirdView.backgroundColor = [UIColor grayColor];
thirdView.tag = 1;
thirdView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self createUIViews];
// Set up the views array with 3 UIImageViews
views = [[NSArray alloc] initWithObjects:firstView, secondView, thirdView, nil];
// Set pageControl's numberOfPages to 3
self.pageControl.numberOfPages = [views count];
// Set pageControl's currentPage to 0
self.pageControl.currentPage = 0;
// Call changePage each time value of pageControl changes
[self.pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
}
- (IBAction) changePage:(id)sender {
NSLog(#"pageControl position %d", [self.pageControl currentPage]);
int oldPageControlPosition = [self.pageControl currentPage] - 1;
NSLog(#"old pageControl position %d", oldPageControlPosition);
//0 Get the currentview as referenced by pageControl
UIImageView *oldView = [views objectAtIndex:oldPageControlPosition];
//NSLog(#"views objectAtIndex = %#",[views objectAtIndex:[self.pageControl currentPage]]);
//1 Animate out the old view
CGRect oldViewFrame = oldView.frame;
oldViewFrame.origin.x -= 300;
[UIView animateWithDuration:2.0
delay: 0.5
options: UIViewAnimationOptionCurveEaseIn
animations:^{
oldView.frame = oldViewFrame;
}
completion:nil];
//3 Get next view from array
UIImageView *nextView = [views objectAtIndex:[self.pageControl currentPage]];
//4 Add it to mainview
[self.view addSubview:nextView];
//5 Animate in
CGRect nextViewFrame = nextView.frame;
nextViewFrame.origin.x += 40; // shift right by 50pts
nextViewFrame.origin.y += 40;
[UIView animateWithDuration:1.0
animations:^{
nextView.frame = nextViewFrame;
}];
}
When I reach the end, I try to return, the last position is 2 and oldPosition at that time is 1. Which is correct, array goes from 0 to 1 to 2 for a total of 3 positions. But when I return, the log displays position as 1 instead of 2, which is fine, because I reversed...but old position shows 0 instead of 2.
I couldnt get it to determine direction so I ended up using gesture recognizers with swipe left and swipe right instances. Here is the code:
//Help determine direction of swipe
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeNext:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.scrollView addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipePrev:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.scrollView addGestureRecognizer:swipeRight];
I made an App using cocos2D that has a hierarchical structure.
And I used a UIButton on glView in a child layer.
When I get back to parent layer, the button still on it's position.
I want to terminate that.
How can I do this?
Here's the code.
MainHallLayer.m
- (id)init
{
self = [super init];
if (self != nil)
{
CCMenu *menuLists = [CCMenu menuWithItems: nil];
menuLists.position = ccp(screenSize.width/2, screenSize.height/2);
[self addChild:menuLists z:10];
NSString *fontName = [NSString stringWithFormat:#"Chalkboard SE"];
CGFloat fontSize = 28;
{
CCLabelTTF *label = [CCLabelTTF labelWithString:#"Touch Field : Getting
touches coordinates" fontName:fontName fontSize:fontSize];
[label setColor:ccc3(0.0, 0.0, 0.0)];
label.anchorPoint = ccp(0, 0.5f);
CCMenuItem *menuItem = [CCMenuItemLabel itemWithLabel:label block:^(id
sender)
{
CCScene *scene = [TouchField1Layer node];
[ReturningNode returnToNodeWithParent:scene];
[[CCDirector sharedDirector] replaceScene:scene];
}];
[menuLists addChild:menuItem];
}
}
return self;
}
ReturnToNode.m
- (id)initWithParentNode:(CCNode *)parentNode
{
self = [super init];
if (self != nil)
{
CGSize screenSize = [[CCDirector sharedDirector]winSize];
CCLabelTTF *label = [CCLabelTTF labelWithString:#" <= Return"
fontName:#"Gill Sans"
fontSize:30.0f];
label.color = ccMAGENTA;
id tint_1 = [CCTintTo actionWithDuration:0.333f red:1.0 green:.0f blue:.0f];
id tint_2 = [CCTintTo actionWithDuration:0.333f red:.5f green:.5f blue:.0f];
id tint_3 = [CCTintTo actionWithDuration:0.333f red:.0f green:1.0 blue:.0f];
id tint_4 = [CCTintTo actionWithDuration:0.333f red:.0f green:.5f blue:.5f];
id tint_5 = [CCTintTo actionWithDuration:0.333f red:.0f green:.0f blue:1.0];
id tint_6 = [CCTintTo actionWithDuration:0.333f red:.5f green:.0f blue:.5f];
id sequence = [CCSequence actions:tint_1,tint_2,tint_3,tint_4,tint_5,tint_6, nil];
id repeatAction = [CCRepeatForever actionWithAction:sequence];
[label runAction:repeatAction];
CCLayerColor *labelBackground = [CCLayerColor layerWithColor:ccc4(0.0, 0.0, 70, 40) width:label.contentSize.width + 20 height:label.contentSize.height + 20];
[label addChild:labelBackground z:-1];
CCMenuItem *menuItem = [CCMenuItemLabel itemWithLabel:label block:^(id sender)
{
[self removeFromParentAndCleanup:YES];
[[CCDirector sharedDirector] replaceScene:[TouchControllerLayer scene]];
}];
CCMenu *menu = [CCMenu menuWithItems:menuItem, nil];
[menu alignItemsVertically];
menu.position = CGPointMake(label.contentSize.width/2 , screenSize.height - 20);
[self addChild:menu];
[parentNode addChild:self z:1000];
}
return self;
}
+ (id)returnToNodeWithParent:(CCNode *)parentNode
{
return [[[self alloc] initWithParentNode:parentNode] autorelease];
}
TouchField1Layer.m
- (id)init
{
self = [super init];
if (self != nil)
{
BackgroundLayer *background = [BackgroundLayer node];
TouchField3Layer *layer = [TouchField3Layer node];
[self addChild:background z:3];
[self addChild:layer z:2];
[self preparingTools];
}
return self;
}
- (void)preparingTools
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, 100, 40);
UIView *glView = [CCDirector sharedDirector].openGLView;
glView.tag = TAG_GLVIEW;
[glView addSubview:button];
}
Any advices, helps are welcome. Always thanks. Bless You.
If you add UIKit views you will have to remove them manually at the appropriate point in time. Cocos2D does not manage the lifetime of UIKit views, only classes derived from CCNode.
For example when changing scenes you will have to remove the UIButton from the glView either in -(void) dealloc or in -(void) cleanup.
I am trying to create a page turn application in xcode. The page turn works fine for landscape right but for landscape left, the page curl happens from the left. I added a container view and then the page curl on landscape left started happening from the bottom but not from right.
I found some suggestions here (http://stackoverflow.com/questions/4780488/i-want-to-use-animation-to-imageview-using-uianimationtransitioncurl-right-or-lef) and here (http://stackoverflow.com/questions/4780488/i-want-to-use-animation-to-imageview-using-uianimationtransitioncurl-right-or-lef)
but these both suggestions were with old style of page transition code and not with the block code. I tried to modify these with new block style code but it is not working for me.
I am attaching my code here:
- (void)viewDidLoad
{
UIImage *img = [UIImage imageNamed:#"s1p1.png"];
currentView.image = img;
img = [UIImage imageNamed:#"s1p2.png"];
swapView.image = img;
UISwipeGestureRecognizer *nextPage;
nextPage = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(turnPage)] autorelease];
if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft) {
[nextPage setDirection:UISwipeGestureRecognizerDirectionRight];
}
else {
[nextPage setDirection:UISwipeGestureRecognizerDirectionLeft];
}
[self.view addGestureRecognizer:nextPage];
[super viewDidLoad];
}
-(void) turnPage
{
if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft)
{
NSLog(#"landscapeleft");
mainView.transform = CGAffineTransformMakeRotation(M_PI);
currentView.transform = CGAffineTransformMakeRotation(-M_PI);
swapView.transform = CGAffineTransformMakeRotation(-M_PI);
[UIView transitionWithView:mainView
duration:1
options:UIViewAnimationOptionTransitionCurlUp
animations:^{
currentView.hidden = YES;
swapView.hidden = NO;
}
completion:^(BOOL finished){
UIImage *temp = [currentView.image retain];
currentView.image = swapView.image;
swapView.image = temp;
[temp release];
currentView.hidden = NO;
swapView.hidden = YES;
}];
}
else
{
NSLog(#"landscaperight");
[UIView transitionWithView:self.view
duration:1
options:UIViewAnimationOptionTransitionCurlUp
animations:^{
currentView.hidden = YES;
swapView.hidden = NO;
}
completion:^(BOOL finished){
UIImage *temp = [currentView.image retain];
currentView.image = swapView.image;
swapView.image = temp;
[temp release];
currentView.hidden = NO;
swapView.hidden = YES;
}];
}
}
where I have two views: the self.view is the primary view from the window and then the mainView is my container view. currentView and SwapView are imageviews.
Any thoughts on this? Many thanks for reviewing this.
How can I open a view when I clicked on annotation's button with a navigation button to go back to my mapkit and pass some parameters to the view?
Regards
I have found a solution. Inside:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
Add:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[btn addTarget:self action:#selector(pinTouched:) forControlEvents:UIControlEventTouchUpInside];
Then have a function to open the desired view:
-(void)pinTouched:(UIButton *)sender
{
myView.transform = CGAffineTransformMakeScale(.01, .01);
[self.view addSubview:myView];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
...
...
...
//important
//otherwise calloutAccessoryControlTapped not called
pin.canShowCallout = YES;
pin.calloutOffset = CGPointMake(-10, -10);
UIImageView *leftIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"some.png"]];
leftIconView.backgroundColor = [UIColor clearColor];
leftIconView.contentMode = UIViewContentModeScaleAspectFit;
leftIconView.frame = CGRectMake(0, 0, 40, 40);
pin.leftCalloutAccessoryView = leftIconView;
....
....
return pin;
}
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
// annotation tapped
float viewWidth = 100;
float viewHeight = 300;
float viewX = 50;
float viewY = 50;
CGRect viewRect = CGRectMake(viewX,viewY, viewWidth, viewHeight);
UIView *viewSub = [[UIView alloc] initWithFrame:viewRect];
viewSub.backgroundColor = [UIColor redColor];
viewSub.tag = 666;
[self.view addSubview:viewSub];
[self.view bringSubviewToFront:viewSub];
}
I have a UITextField in a table view on a UIViewController (not a UITableViewController).
If the table view is on a UITableViewController, the table will automatically scroll to the textField being edited to prevent it from being hidden by the keyboard. But on a UIViewController it does not.
I have tried for a couple of days reading through multiple ways to try to accomplish this and I cannot get it to work. The closest thing that actually scrolls is:
-(void) textFieldDidBeginEditing:(UITextField *)textField {
// SUPPOSEDLY Scroll to the current text field
CGRect textFieldRect = [textField frame];
[self.wordsTableView scrollRectToVisible:textFieldRect animated:YES];
}
However this only scrolls the table to the topmost row.
What seems like an easy task has been a couple of days of frustration.
I am using the following to construct the tableView cells:
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = [NSString stringWithFormat: #"%d:%d", [indexPath indexAtPosition: 0], [indexPath indexAtPosition:1]];
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 10, 130, 25)];
theTextField.adjustsFontSizeToFitWidth = YES;
theTextField.textColor = [UIColor redColor];
theTextField.text = [textFieldArray objectAtIndex:indexPath.row];
theTextField.keyboardType = UIKeyboardTypeDefault;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.font = [UIFont boldSystemFontOfSize:14];
theTextField.backgroundColor = [UIColor whiteColor];
theTextField.autocorrectionType = UITextAutocorrectionTypeNo;
theTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
theTextField.clearsOnBeginEditing = NO;
theTextField.textAlignment = UITextAlignmentLeft;
//theTextField.tag = 0;
theTextField.tag=indexPath.row;
theTextField.delegate = self;
theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
[theTextField setEnabled: YES];
[cell addSubview:theTextField];
[theTextField release];
}
return cell;
}
I suspect I can get the tableView to scroll properly if I can somehow pass the indexPath.row in the textFieldDidBeginEditing method?
Any help is appreciated.
In my app, I have successfully used a combination of contentInset and scrollToRowAtIndexPath like this:
When you want to display the keyboard, just add a contentInset at the bottom with your table with desired height:
tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
Then, you can safely use
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:cell_index inSection:cell_section] animated:YES];
By adding the contentInset, even if you are focusing on the last cell the tableView will still be able to scroll. Just make sure that when you are dismissing the keyboard, you reset the contentInset.
EDIT:
If you have only one section (you can replace cell_section with 0) and the use the textView tag to inform the cell row.
Swift
#objc private func keyboardWillShow(_ notification: Notification) {
guard let userinfo = notification.userInfo else {
return
}
guard
let duration = (userinfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let endFrame = (userinfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let curveOption = userinfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt else {
return
}
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .init(rawValue: curveOption)], animations: {
let edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: endFrame.height, right: 0)
self.scrollView.contentInset = edgeInsets
self.scrollView.scrollIndicatorInsets = edgeInsets
})
}
#objc private func keyboardWillHide(_ notification: Notification) {
guard let userinfo = notification.userInfo else {
return
}
guard
let duration = (userinfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let curveOption = userinfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt else {
return
}
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .init(rawValue: curveOption)], animations: {
let edgeInsets = UIEdgeInsets.zero
self.scrollView.contentInset = edgeInsets
self.scrollView.scrollIndicatorInsets = edgeInsets
})
}
override func viewDidLoad() {
super.viewDidLoad()
// ...
subscribeToKeyboardNotifications()
}
deinit {
unsubscribeFromKeyboardNotifications()
}
private func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIWindow.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIWindow.keyboardWillHideNotification, object: nil)
}
private func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillHideNotification, object: nil)
}
Objective C
- (void)keyboardWillShow:(NSNotification *)sender
{
CGFloat height = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
NSTimeInterval duration = [[sender.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationOptions curveOption = [[sender.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|curveOption animations:^{
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, height, 0);
tableView.contentInset = edgeInsets;
tableView.scrollIndicatorInsets = edgeInsets;
} completion:nil];
}
- (void)keyboardWillHide:(NSNotification *)sender
{
NSTimeInterval duration = [[sender.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationOptions curveOption = [[sender.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|curveOption animations:^{
UIEdgeInsets edgeInsets = UIEdgeInsetsZero;
tableView.contentInset = edgeInsets;
tableView.scrollIndicatorInsets = edgeInsets;
} completion:nil];
}
And in - (void)viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
Then
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
This is a tweak to FunkyKat's answer (big thank you FunkyKat!). It would probably be beneficial to not hardcode UIEdgeInsetsZero for future iOS compatibility.
Instead, I ask for the current inset value and tweak the bottom value as needed.
- (void)keyboardWillShow:(NSNotification *)sender {
CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.height : kbSize.width;
if (isIOS8()) height = kbSize.height;
[UIView animateWithDuration:duration animations:^{
UIEdgeInsets edgeInsets = [[self tableView] contentInset];
edgeInsets.bottom = height;
[[self tableView] setContentInset:edgeInsets];
edgeInsets = [[self tableView] scrollIndicatorInsets];
edgeInsets.bottom = height;
[[self tableView] setScrollIndicatorInsets:edgeInsets];
}];
}
- (void)keyboardWillHide:(NSNotification *)sender {
NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
UIEdgeInsets edgeInsets = [[self tableView] contentInset];
edgeInsets.bottom = 0;
[[self tableView] setContentInset:edgeInsets];
edgeInsets = [[self tableView] scrollIndicatorInsets];
edgeInsets.bottom = 0;
[[self tableView] setScrollIndicatorInsets:edgeInsets];
}];
}
For the sake of anyone else running into this issue, I'm posting the necessary methods here:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = [NSString stringWithFormat: #"%d:%d", [indexPath indexAtPosition: 0], [indexPath indexAtPosition:1]];
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 10, 130, 25)];
theTextField.keyboardType = UIKeyboardTypeDefault;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.clearsOnBeginEditing = NO;
theTextField.textAlignment = UITextAlignmentLeft;
// (The tag by indexPath.row is the critical part to identifying the appropriate
// row in textFieldDidBeginEditing and textFieldShouldEndEditing below:)
theTextField.tag=indexPath.row;
theTextField.delegate = self;
theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
[theTextField setEnabled: YES];
[cell addSubview:theTextField];
[theTextField release];
}
return cell;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField {
int z = textField.tag;
if (z > 4) {
// Only deal with the table row if the row index is 5
// or greater since the first five rows are already
// visible above the keyboard
// resize the UITableView to fit above the keyboard
self.wordsTableView.frame = CGRectMake(0.0,44.0,320.0,200.0);
// adjust the contentInset
wordsTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 10);
// Scroll to the current text field
[wordsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:z inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
// Determine which row is being edited
int z = textField.tag;
if (z > 4) {
// resize the UITableView to the original size
self.wordsTableView.frame = CGRectMake(0.0,44.0,320.0,416.0);
// Undo the contentInset
wordsTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// Dismisses the keyboard when the "Done" button is clicked
[textField resignFirstResponder];
return YES;
}
I needed a simple solution so for me helped:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
let pointInTable = textField.superview!.convert(textField.frame.origin, to: tableView)
var tableVContentOffset = tableView.contentOffset
tableVContentOffset.y = pointInTable.y
if let accessoryView = textField.inputAccessoryView {
tableVContentOffset.y -= accessoryView.frame.size.height
}
tableView.setContentOffset(tableVContentOffset, animated: true)
return true;
}
Try my coding, this will help for ypu
tabelview.contentInset = UIEdgeInsetsMake(0, 0, 210, 0);
[tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:your_indexnumber inSection:Your_section]
atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
Apple has an official post explaining how to do this naturally as they do in the UITableViewController. My Stackoverflow answer has this explained along with a swift version.
https://stackoverflow.com/a/31869898/1032179
You need to resize the tableView itself so that it does not go under the keyboard.
-(void) textFieldDidBeginEditing:(UITextField *)textField {
// SUPPOSEDLY Scroll to the current text field
self.worldsTableView.frame = CGRectMake(//make the tableView smaller; to only be in the area above the keyboard);
CGRect textFieldRect = [textField frame];
[self.wordsTableView scrollRectToVisible:textFieldRect animated:YES];
}
Alternatively, you can use a keyboard notification; this works slightly better because you have more information, and is more consistent in terms of knowing when the keyboard is coming up:
//ViewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
And then implement:
- (void)keyboardWillShow:(NSNotification *)notification {
}
- (void)keyboardWillHide:(NSNotification *)notification {
}
My code. Maybe someone will be useful:
Custom textField cell in tableView
.m
#property (nonatomic, strong) UITextField *currentCellTextField;
CustomCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
NSArray * nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = (CustomCell *)[nib objectAtIndex:0];
cell.textfield.delegate = self;
}
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
self.currentCellTextField = textField;
CGPoint pnt = [self.organisationTableView convertPoint:textField.bounds.origin fromView:textField];
NSIndexPath* path = [self.organisationTableView indexPathForRowAtPoint:pnt];
if (path.section >= 2) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.organisationTableView.contentInset = UIEdgeInsetsMake(0, 0, kOFFSET_FOR_KEYBOARD, 0);
CGPoint siize = self.organisationTableView.contentOffset;
siize.y =(pnt.y-170);
self.organisationTableView.contentOffset = CGPointMake(0, siize.y);
[UIView commitAnimations];
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
CGPoint pnt = [self.organisationTableView convertPoint:textField.bounds.origin fromView:textField];
NSIndexPath* path = [self.organisationTableView indexPathForRowAtPoint:pnt];
if (path.section >= 2) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.organisationTableView.contentInset = UIEdgeInsetsZero;
self.organisationTableView.contentOffset = CGPointMake(0, self.organisationTableView.contentOffset.y);
[UIView commitAnimations];
}
return YES;
}
In my case my UITableview was inside another UIView and that UIvie was in the main UIScrollview. So I used more general solution for those kind of problems.
I simply found the Y coordinate of my cell in the specific UIScrollView and then scrolled to correct point:
-(void)textFieldDidBeginEditing:(UITextField *)textField{
float kbHeight = 216;//Hard Coded and will not support lanscape mode
UITableViewCell *cell = (UITableViewCell *)[textField superview];
float scrollToHeight = [self FindCordinate:cell];
[(UIScrollView *)self.view setContentOffset:CGPointMake(0, scrollToHeight - kbHeight + cell.frame.size.height) animated:YES];
}
-(float)FindCordinate:(UIView *)cell{
float Ycordinate = 0.0;
while ([cell superview] != self.view) {
Ycordinate += cell.frame.origin.y;
cell = [cell superview];
}
Ycordinate += cell.frame.origin.y;
return Ycordinate;
}
Another simple solution is adding an additional space for the footer of the last table section:
- (float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
if (section == lastSection) {
return keyboard height;
}
return 0;
}
We can add our icon into this area as well. :)
You can try adding a UITableViewController to the UIViewController instead of just a table view. This way you can call UITableViewController's viewWillAppear and everything will appear to work.
Example:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[tableViewController viewWillAppear:animated];
}
I have add a little feature to #FunkyKat and #bmauter answers (great answer by the way, it should be the one accepted)
The regular Table View edge insets is preserved, before/after the keyboard apparition.
- (void)keyboardWillShow:(NSNotification *)sender
{
CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height;
[UIView animateWithDuration:duration animations:^{
UIEdgeInsets edgeInsets = self.tableView.contentInset;
edgeInsets.bottom += height;
self.tableView.contentInset = edgeInsets;
edgeInsets = self.tableView.scrollIndicatorInsets;
edgeInsets.bottom += height;
self.tableView.scrollIndicatorInsets = edgeInsets;
}];
}
- (void)keyboardWillHide:(NSNotification *)sender
{
CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height;
[UIView animateWithDuration:duration animations:^{
UIEdgeInsets edgeInsets = self.tableView.contentInset;
edgeInsets.bottom -= height;
self.tableView.contentInset = edgeInsets;
edgeInsets = self.tableView.scrollIndicatorInsets;
edgeInsets.bottom -= height;
self.tableView.scrollIndicatorInsets = edgeInsets;
}];
}