Animate the height of inputAccessoryView Swift

2019-05-29 10:32发布

问题:

Hello I' trying to change the height of a button set as inputAccessoryView once I click on it.

Unfortunately it seems only to change the position but not the height.

Can Anyone help me out? Below my code.

Thank you!

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {



 @IBOutlet var textField: UITextField!

    var SendButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton

    override func viewDidLoad() {
        super.viewDidLoad()

        SendButton.frame = CGRectMake(0, 0, UIScreen.mainScreen().applicationFrame.width, 30)
        SendButton.backgroundColor = UIColor(red: 184/255.0, green: 56/255.0, blue: 56/255.0, alpha: 1)
        SendButton.setTitle("Send", forState: .Normal)
        SendButton.addTarget(self, action: "sendNotification", forControlEvents: UIControlEvents.AllEvents)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func sendNotification(){

        UIView.animateWithDuration(1, animations: {
            self.SendButton.frame = CGRectMake(0, -340, UIScreen.mainScreen().applicationFrame.width, 30)
            self.SendButton.backgroundColor = UIColor(red: 300/255.0, green: 56/255.0, blue: 56/255.0, alpha: 1)
            self.SendButton.setTitle("Hello", forState: .Normal)

        })
    }


    func textFieldDidBeginEditing(textField: UITextField) {
        textField.inputAccessoryView = self.SendButton
    }

}

回答1:

In your animation block you are changing the y posistion of the frame in CGRectMake rather than the height. that's why the position is changing and not the height.

 UIView.animateWithDuration(1, animations: {
 // Your problem is the line below
        self.SendButton.frame = CGRectMake(0, -340, UIScreen.mainScreen().applicationFrame.width, 30) 
    })

The function parameters of the function CGRectMake are
CGRectMake(xPosition, yPosition, width, height)

Change the code below to your desired height.

   UIView.animateWithDuration(1, animations: {
        self.SendButton.frame = CGRectMake(0, 0, UIScreen.mainScreen().applicationFrame.width, yourDesiredHeight) 
    })

But this doesn't help in changing the height of the input accessory once it was set.

First add a separate UIView as input accessory(with added height) and add the button into this UIView. Animate the button inside after that. This works. You can check out the code in the gist
https://gist.github.com/rakeshbs/539827925df923e41afe