带有Textfield的KeyBoard一起动画进入视图

时间:2015-03-09 13:02:49

标签: ios uitextfield uikeyboard

我希望在NumberPad上方有一个文本字段,以便在点击showKeyboard时,UIView(带有textfield和" add"按钮)+ NumberPad一起动画显示在视图中。我可以单独查看它们,但不能同时查看..我不确定会发生什么。如果我按showKeyboard一次,则会出现数字键,如果我再次按下UIView(带有textfield和"添加"按钮)动画进入视图。如何同时将numberPad和UIView转换为视图? 非常感谢任何帮助!

class ViewController: UIViewController{

    @IBOutlet var showKeyboard: UIButton!
    @IBOutlet var containerView: UIView!
    @IBOutlet var inputField: UITextField!
    @IBOutlet var addData: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func didTapshowKeyboard(sender: AnyObject) {

        inputField.keyboardType = UIKeyboardType.NumberPad
        inputField.becomeFirstResponder()

        let height = containerView.frame.size.height
        let width = containerView.frame.size.width

        //New X Position (same)
        let xPosition = containerView.frame.origin.x // i.e. 0

        //New Y position
        let yPosition = containerView.frame.origin.y - 270

        UIView.animateWithDuration(0.3, animations: {
            self.containerView.frame = CGRect(x: 0, y: yPosition, width: width , height: height) })

        println("tapped")
    }
}

NUmberPad with textfield

1 个答案:

答案 0 :(得分:1)

您应该在keyboardWillShow通知程序中执行所有动画计算:(将_textField替换为包含您要显示的所有元素的视图。请注意,一旦您的文本字段成为第一响应者,此方法将触发。)

- (void)keyboardWillShow:(NSNotification *)notification {
     //this is the time interval for the animation time
    NSTimeInterval animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    NSInteger animationCurve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    //Get the keyboard frame to calculate your UITextField position
    CGRect keybFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

   //set the textField frame to bottom of screen, before animating it up with the keyboard
   _textField.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, kTextFieldHeight);

   //setting a new frame to the textField
   CGRect frame = CGRectMake(0, (self.view.frame.size.height - keybFrame.size.height) - kTextFieldHeight, self.view.frame.size.width, kTextFieldHeight);

   [UIView animateWithDuration:animationDuration delay:0.0 options:animationCurve animations:^{
        //Making it visible
       _textField.alpha = 1.0;
       _textField.frame = frame;
   } completion:^(BOOL finished) {}];
}