Hiding the Keyboard when losing focus on a UITextView

后端 未结 10 565
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 10:34

So I have a UITextView that I\'m using to allow the user to submit some text.

My problem is, I can\'t seem to figure out how to allow the user to \'Cancel\' by tappi

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 10:43

    I wanted a version of this that worked for resigning from any view, without requiring specific outlets for each one.. Here is my solution, which I put into one of my standard container views..

    It's using MonoTouch C#, though it should be obvious how to convert it to Objective-C

        private void findAndResignFirstResponder(UIView node=null) {
            if (node == null) { return; }
            if (node.IsFirstResponder) {
                node.ResignFirstResponder();
                return;
            }
    
            foreach (UIView view in node.Subviews) {
                findAndResignFirstResponder(node:view);
            }
        }
    
        private bool haveDrag = false;
        public override void TouchesEnded(NSSet touches, UIEvent evt) {
            if (!haveDrag) {
                UITouch touch = (UITouch)evt.AllTouches.AnyObject;
                if (!touch.View.CanBecomeFirstResponder) {
                    this.findAndResignFirstResponder(this);
                    Console.WriteLine("resign");
                }
            }
            base.TouchesEnded (touches, evt);
        }
        public override void TouchesMoved(NSSet touches, UIEvent evt) {
            haveDrag = true;
            base.TouchesMoved (touches, evt);
        }
    
        public override void TouchesBegan(NSSet touches, UIEvent evt) {
            haveDrag = false;
            base.TouchesBegan (touches, evt);
        }
    

提交回复
热议问题