欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS键盘自适应弹出效果

程序员文章站 2023-12-19 17:42:34
一、ios键盘自适应弹出效果图 二、工程图 三、代码 viewcontroller.h #import ...

一、ios键盘自适应弹出效果图

iOS键盘自适应弹出效果

二、工程图

iOS键盘自适应弹出效果

三、代码

viewcontroller.h

#import <uikit/uikit.h>

@interface viewcontroller : uiviewcontroller
<uitextfielddelegate>


@end

viewcontroller.m

#import "viewcontroller.h"

@interface viewcontroller ()

@end

@implementation viewcontroller

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  
  
  uitextfield *field=[[uitextfield alloc]initwithframe:cgrectmake(100, 300, 50, 50)];
  field.backgroundcolor=[uicolor redcolor];
  field.delegate=self;
  [self.view addsubview:field];
  
  
  
  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(keyboardwillshow:) name:uikeyboardwillshownotification object:nil];
  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(keyboardwillhide:) name:uikeyboardwillhidenotification object:nil];
  
}
#pragma -mark -keyboard notificatin
- (void)keyboardwillshow:(nsnotification *)notification {
  nsdictionary *info = [notification userinfo];
  // keyboardheight 为键盘高度
  cgsize keyboardsize = [[info objectforkey:uikeyboardframeenduserinfokey] cgrectvalue].size;
  [self animateviewwithkeyboardheight:keyboardsize.height];
}

- (void)keyboardwillhide:(nsnotification *)notification {
  [self animateviewwithkeyboardheight:0.0];
}

- (void)animateviewwithkeyboardheight:(cgfloat)keyboardheight {
  nstimeinterval animationduration = 0.3f;
  cgfloat height = self.view.bounds.size.height;
  cgfloat width = self.view.bounds.size.width;
  cgfloat topsize = 0.0;
  cgfloat viewh = self.view.frame.size.height-64;
  cgfloat deviceheight = [uiscreen mainscreen].bounds.size.height;
  cgfloat animateh = deviceheight - viewh - keyboardheight;
  if (animateh >= 0) {
    topsize = 0;
    cgrect torect = cgrectmake(0, topsize, width, height);
    self.view.frame = torect;
    
  } else {
    topsize = animateh;
    cgrect torect = cgrectmake(0, topsize, width, height);
    [uiview animatewithduration:animationduration animations:^{
      self.view.frame = torect;
    }];
  }
}
#pragma -mark -uitextfielddelegate
-(bool)textfieldshouldreturn:(uitextfield *)textfield
{
  [textfield resignfirstresponder];
  
  return yes;
}

- (void)didreceivememorywarning {
  [super didreceivememorywarning];
  // dispose of any resources that can be recreated.
}


@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: