• iOS TPKeyboardAvoiding自动识别键盘的高度


                    

    #import <UIKit/UIKit.h>
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate>
    
    @property (strong, nonatomic) UIWindow *window;
    
    
    @end
    #import "AppDelegate.h"
    #import "RootViewController.h"
    @interface AppDelegate ()
    
    @end
    
    @implementation AppDelegate
    
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.window.backgroundColor = [UIColor whiteColor];
        
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:[[RootViewController alloc] init]];
        self.window.rootViewController = navi;
        
        [self.window makeKeyAndVisible];
        return YES;
    }
    
    @end
    #import <UIKit/UIKit.h>
    #import "TPKeyboardAvoidingScrollView.h"
    
    @interface RootViewController : UIViewController
    
    @property(nonatomic, assign) NSInteger id;
    //@property(nonatomic, copy) NSString *name;//姓名
    //@property(nonatomic, copy) NSString *bankAccount;//银行账号
    //@property(nonatomic, copy) NSString *bankName;// 开户的银行
    @property(nonatomic, strong) TPKeyboardAvoidingScrollView *backgroundView;//背景图
    
    @end
    #import "RootViewController.h"
    
    #define WIDTH [UIScreen mainScreen].bounds.size.width
    #define TAG 10000
    #define topHeight 20
    
    @interface RootViewController ()
    {
        UIImageView *lineView;
    }
    @end
    
    @implementation RootViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //适配ios7
        if([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
            self.extendedLayoutIncludesOpaqueBars = NO;
            self.modalPresentationCapturesStatusBarAppearance = NO;
        }
        self.title = @"绑定银行卡";
        
        _backgroundView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, [UIScreen mainScreen].bounds.size.height - 64)];
    //    _backgroundView.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:_backgroundView];
    
        //初始化label
        [self setupLable:CGRectMake(0, topHeight, 90, 30) title:@"开户银行:"];
        [self setupLable:CGRectMake(0, topHeight+40, 90, 30) title:@"开户归属地:"];
        [self setupLable:CGRectMake(0, topHeight+80, 90, 30) title:@"姓   名:"];
        [self setupLable:CGRectMake(0, topHeight+120, 90, 30) title:@"账   号:"];
        [self setupLable:CGRectMake(0, topHeight+160, 90, 30) title:@"验证码:"];
        //初始化银行类型textField
        [self setupTextField:CGRectMake(95, topHeight, (WIDTH - 5)-95, 30) placeholder:@"请输入银行类型" index:1];
        //初始化省份textField
        UITextField *provinceTF = [self setupTextField:CGRectMake(95, topHeight+40,(WIDTH - 5 - (14+6) - 95)/2.0, 30) placeholder:@"请输入省份" index:2];
        //小细线
        lineView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(provinceTF.frame)+3, CGRectGetMidY(provinceTF.frame), 14, 1)];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [self.backgroundView addSubview:lineView];
        //初始化地级市textField
        [self setupTextField:CGRectMake(CGRectGetMaxX(lineView.frame)+3, topHeight+40, (WIDTH - 5 - (14+6) - 95)/2.0, 30) placeholder:@"请输入地级市" index:3];
        //初始化姓名textField
        [self setupTextField:CGRectMake(95, topHeight+80, (WIDTH - 5)-95, 30) placeholder:@"请输入姓名" index:4];
        //初始化银行账号textField
        [self setupTextField:CGRectMake(95, topHeight+120, (WIDTH - 5)-95, 30) placeholder:@"请输入银行账号" index:5];
        //初始化验证码textField(100是获取验证码按钮的宽度)
        UITextField *securityCodeTF = [self setupTextField:CGRectMake(95, topHeight+160, (WIDTH - 5)-95 - 100 - 5, 30) placeholder:@"验证码" index:6];
        //初始化确定按钮
        [self setupButton:CGRectMake((WIDTH - 200)/2.0,CGRectGetMaxY(securityCodeTF.frame)+15 /*_backgroundView.frame.size.height - 30*/, 200, 30) title:@"确定" image:@"确定按钮.png" selector:@selector(makeSureAction:)];
       
        //初始化获取验证码按钮
        [self setupButton:CGRectMake(CGRectGetMaxX(securityCodeTF.frame)+5 , topHeight+160, 100, 30) title:@"获取验证码" image:@"矩形-2.png" selector:@selector(getSecurityCode:)];
        
        
    }
    /**
     *  获取验证码
     */
    - (void)getSecurityCode:(UIButton *)sender{
        NSLog(@"获取验证码操作");
    }
    
    // 点击确定按钮,提交数据
    - (void)makeSureAction:(UIButton *)sender{
        NSLog(@"提交前需要判断");
    }
    /**
     *  初始化button
     */
    - (void)setupButton:(CGRect)frame title:(NSString *)title image:(NSString *)imageName selector:(SEL)selectorName{
        UIButton *securityCode = [UIButton buttonWithType:UIButtonTypeCustom];
        securityCode.frame = frame;
        securityCode.layer.cornerRadius = 5.2;
        [securityCode setTitle:title forState:0];
        securityCode.clipsToBounds = YES;
        securityCode.titleLabel.font = [UIFont systemFontOfSize:15];
        [securityCode setBackgroundImage:[UIImage imageNamed:imageName] forState:0];
        [securityCode addTarget:self action:selectorName forControlEvents:UIControlEventTouchUpInside];
        [self.backgroundView addSubview:securityCode];
    }
    /**
     *  初始化UITextField
     */
    - (UITextField *)setupTextField:(CGRect)frame placeholder:(NSString *)context index:(NSInteger)tag{
        UITextField *tf = [[UITextField alloc] initWithFrame:frame];
        tf.font = [UIFont systemFontOfSize:13];
        tf.placeholder = context;
        tf.tag = TAG + tag;
        tf.borderStyle = UITextBorderStyleRoundedRect;
        [self.backgroundView addSubview:tf];
        return tf;
    }
    /**
     *  初始化UILabel
     */
    - (void)setupLable:(CGRect)frame title:(NSString*)content{
        UILabel *label = [[UILabel alloc] initWithFrame:frame];
        label.text = content;
        label.font = [UIFont systemFontOfSize:15];
        label.textAlignment = NSTextAlignmentRight;
        [self.backgroundView addSubview:label];
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)even{
        [self.view endEditing:YES];
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
       
    }
    
    
    
    @end
    /**
     *  第三方框架(TPKeyboardAvoiding)的代码
     */
    #import <UIKit/UIKit.h>
    
    @interface TPKeyboardAvoidingScrollView : UIScrollView{
        
        UIEdgeInsets    _priorInset;
        BOOL            _priorInsetSaved;
        BOOL            _keyboardVisible;
        CGRect          _keyboardRect;
        CGSize          _originalContentSize;
    }
    
    - (void)adjustOffsetToIdealIfNeeded;
    
    @end
    /**
     *  第三方框架(TPKeyboardAvoiding)的代码
     */
    #import "TPKeyboardAvoidingScrollView.h"
    
    #define _UIKeyboardFrameEndUserInfoKey (&UIKeyboardFrameEndUserInfoKey != NULL ? UIKeyboardFrameEndUserInfoKey : @"UIKeyboardBoundsUserInfoKey")
    
    #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
    #define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
    
    @interface TPKeyboardAvoidingScrollView ()
    - (UIView*)findFirstResponderBeneathView:(UIView*)view;
    - (UIEdgeInsets)contentInsetForKeyboard;
    - (CGFloat)idealOffsetForView:(UIView *)view withSpace:(CGFloat)space;
    - (CGRect)keyboardRect;
    @end
    
    @implementation TPKeyboardAvoidingScrollView
    
    - (void)setup {
        _priorInsetSaved = NO;
        if ( CGSizeEqualToSize(self.contentSize, CGSizeZero) ) {
            self.contentSize = self.bounds.size;
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    -(id)initWithFrame:(CGRect)frame {
        if ( !(self = [super initWithFrame:frame]) ) return nil;
        [self setup];
        return self;
        
    }
    
    -(void)awakeFromNib {
        [self setup];
    }
    
    -(void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [super dealloc];
    }
    
    -(void)setFrame:(CGRect)frame {
        [super setFrame:frame];
        
        CGSize contentSize = _originalContentSize;
        contentSize.width = MAX(contentSize.width, SCREEN_WIDTH);
        contentSize.height = MAX(contentSize.height, SCREEN_HEIGHT-64);
        [super setContentSize:contentSize];
        
        if ( _keyboardVisible ) {
            self.contentInset = [self contentInsetForKeyboard];
        }
    }
    
    -(void)setContentSize:(CGSize)contentSize {
        _originalContentSize = contentSize;
        
        contentSize.width = MAX(contentSize.width, contentSize.width);
        contentSize.height = MAX(contentSize.height, contentSize.height);
        [super setContentSize:contentSize];
        
        if ( _keyboardVisible ) {
            self.contentInset = [self contentInsetForKeyboard];
        }
    }
    
    - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        [[self findFirstResponderBeneathView:self] resignFirstResponder];
        [super touchesEnded:touches withEvent:event];
    }
    
    - (void)keyboardWillShow:(NSNotification*)notification {
        _keyboardRect = [[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue];
        _keyboardVisible = YES;
        
        UIView *firstResponder = [self findFirstResponderBeneathView:self];
        if ( !firstResponder ) {
            // No child view is the first responder - nothing to do here
            return;
        }
        
        if (!_priorInsetSaved) {
            _priorInset = self.contentInset;
            _priorInsetSaved = YES;
        }
        
        // Shrink view's inset by the keyboard's height, and scroll to show the text field/view being edited
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        [UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
        
        self.contentInset = [self contentInsetForKeyboard];
        [self setContentOffset:CGPointMake(self.contentOffset.x,
                                           [self idealOffsetForView:firstResponder withSpace:[self keyboardRect].origin.y - self.bounds.origin.y])
                      animated:YES];
        
        [UIView commitAnimations];
    }
    
    - (void)keyboardWillHide:(NSNotification*)notification {
        _keyboardRect = CGRectZero;
        _keyboardVisible = NO;
        
        // Restore dimensions to prior size
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        [UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
        self.contentInset = _priorInset;
        _priorInsetSaved = NO;
        [UIView commitAnimations];
    }
    
    - (UIView*)findFirstResponderBeneathView:(UIView*)view {
        // Search recursively for first responder
        for ( UIView *childView in view.subviews ) {
            if ( [childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder] ) return childView;
            UIView *result = [self findFirstResponderBeneathView:childView];
            if ( result ) return result;
        }
        return nil;
    }
    
    - (UIEdgeInsets)contentInsetForKeyboard {
        UIEdgeInsets newInset = self.contentInset;
        CGRect keyboardRect = [self keyboardRect];
        newInset.bottom = keyboardRect.size.height - ((keyboardRect.origin.y+keyboardRect.size.height) - (self.bounds.origin.y+self.bounds.size.height));
        return newInset;
    }
    
    -(CGFloat)idealOffsetForView:(UIView *)view withSpace:(CGFloat)space {
        
        // Convert the rect to get the view's distance from the top of the scrollView.
        CGRect rect = [view convertRect:view.bounds toView:self];
        
        // Set starting offset to that point
        CGFloat offset = rect.origin.y;
        
        
        if ( self.contentSize.height - offset < space ) {
            // Scroll to the bottom
            offset = self.contentSize.height - space;
        } else {
            if ( view.bounds.size.height < space ) {
                // Center vertically if there's room
                offset -= floor((space-view.bounds.size.height)/2.0);
            }
            if ( offset + space > self.contentSize.height ) {
                // Clamp to content size
                offset = self.contentSize.height - space;
            }
        }
        
        if (offset < 0) offset = 0;
        
        return offset;
    }
    
    -(void)adjustOffsetToIdealIfNeeded {
        
        // Only do this if the keyboard is already visible
        if ( !_keyboardVisible ) return;
        
        CGFloat visibleSpace = self.bounds.size.height - self.contentInset.top - self.contentInset.bottom;
        
        CGPoint idealOffset = CGPointMake(0, [self idealOffsetForView:[self findFirstResponderBeneathView:self] withSpace:visibleSpace]);
        
        [self setContentOffset:idealOffset animated:YES];
    }
    
    - (CGRect)keyboardRect {
        CGRect keyboardRect = [self convertRect:_keyboardRect fromView:nil];
        if ( keyboardRect.origin.y == 0 ) {
            CGRect screenBounds = [self convertRect:[UIScreen mainScreen].bounds fromView:nil];
            keyboardRect.origin = CGPointMake(0, screenBounds.size.height - keyboardRect.size.height);
        }
        return keyboardRect;
    }
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect {
        // Drawing code
    }
    */
    
    @end
  • 相关阅读:
    Spring Boot 搭建项目阶段Group和Artifact的含义
    设置Mysql数据库账号密码以及时区
    反射
    线程与进程
    网络编程
    队列和栈
    linux下的mysql
    积累的关于linux的安装卸载软件基本命令
    各种url编码
    解决浏览器传值乱码
  • 原文地址:https://www.cnblogs.com/lantu1989/p/5056224.html
Copyright © 2020-2023  润新知