Simple UITextView on the storyboard.
import UIKit
classViewController:UIViewController, UITextViewDelegate{
@IBOutlet weak var hogeTextView: UITextView!
override func viewDidLoad(){
super.viewDidLoad()
self.hogeTextView.delegate=self
NotificationCenter.default.addObserver(self,selector:#selector(keyboardWillChange), name:UIResponder.keyboardWillChangeFrameNotification, object:nil)
NotificationCenter.default.addObserver(self,selector:#selector(keyboardWillHide),name:UIResponder.keyboardWillHideNotification,object:nil)
}
@objc func keyboardWillChange (notification:NSNotification) {
guardlet keyboardSize=notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as?CGRect else {return}
self.view.frame.origin.y = UISscreen.main.bounds.origin.y-keyboardSize.height
}
@objc func keyboardWillHide(notification:NSNotification){
guard self.view.frame.origin.y!=0 else {return}
self.view.frame.origin.y = 0
}
functextView(_textView:UITextView, shouldChangeTextInrange:NSRange, replacementTexttext:String) - >Bool{
if(text=="\n"){
hogeTextView.resignFirstResponder()
return false
}
return true
}
}
This is about the code above.
self.view.frame.origin.y=UISscreen.main.bounds.origin.y-keyboardSize.height
Part of and
self.view.frame.origin.y=0
The UITextView
rises with animation (strictly self.view
) at the same speed as the keyboard rises.Why?
I don't have an environment where I can play with Swift, so I'll explain it quickly.
Behind the UIView is the CALayer.
//UIView
varlayer:CALayer {get}
This instance of CALayer has information about drawing, and UIView draws a view on the screen based on it.CALayer refers to the object responsible for this drawing as a delegate.
//CALayer
weak vardelegate:CALayerDelegate?{getset}
Changing the value of a particular property in UIView is equivalent to changing it in CALayer.CALayer performs "implicit animation" when changing certain values.
Animation is also an object, which is provided by CALayer's delegate, or UIView.UIView conforms to the CALayerDelegate protocol and returns it with the method it implements.
//CALayerDelegate
Optional function (for layer: CALayer, forKey event: String) - > CAAction?
The animation you are interested in is being performed by the animation object returned here.
I think the animation takes 0.25 seconds to draw only the starting and ending points.
action(forKey:)-CALayerDelegate
To learn more from the basics, read the Core Animation Programming Guide.
© 2024 OneMinuteCode. All rights reserved.