键盘打开时以编程方式引发UI文本字段

时间:2015-01-27 22:03:26

标签: ios swift

这是我当前的代码,它可以工作,但是在较小的设备上,字段会移动到用户显示上方。如何编辑它以确保字段不会对用户隐藏?我通过gregbarbosa从tut中偷了一些这样的代码,所以对答案的解释会有很大帮助。谢谢。

import UIKit

class LoginViewController: UIViewController {

//MARK: Storyboard
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var teamID: UITextField!
@IBOutlet weak var scoutID: UITextField!
@IBOutlet weak var pinNum: UITextField!
@IBOutlet weak var signin: UIButton!
@IBOutlet weak var diamondPic: UIImageView!
@IBOutlet weak var nodextext: UILabel!
@IBOutlet weak var loginB: UIButton!
@IBOutlet weak var moverL: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")

    // prevents the scroll view from swallowing up the touch event of child buttons
    tapGesture.cancelsTouchesInView = false

    scrollView.addGestureRecognizer(tapGesture)

}

@IBAction func loginTapped(sender: UIButton) {
    var userDefaults = NSUserDefaults.standardUserDefaults()
    var secretKey = userDefaults.stringForKey("secretkey")
    var team:String = teamID.text
    var scout:String = scoutID.text
    var password:String = pinNum.text


    var loginQuery = PFQuery(className:"User")
    loginQuery.whereKey("teamID", equalTo:team)
    loginQuery.whereKey("scoutID", equalTo:scout)
    loginQuery.whereKey("password", equalTo:password)
    loginQuery.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil && objects.count != 0 {
            self.performSegueWithIdentifier("SecondViewController", sender: self)
        } else if error == nil && objects.count == 0{
            var alert : UIAlertView = UIAlertView(title: "Login Error", message: "Your TeamID, ScoutID, or Password is inncorrect.",       delegate: nil, cancelButtonTitle: "Ok")

            alert.show()

        } else {
            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
    }
}
@IBOutlet weak var loginTapped: UIButton!


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    self.registerForKeyboardNotifications()

}

override func viewWillDisappear(animated: Bool) {
    self.deregisterFromKeyboardNotifications()
    super.viewWillDisappear(true)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func registerForKeyboardNotifications() -> Void {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)

}

func deregisterFromKeyboardNotifications() -> Void {
    println("Deregistering!")
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidHideNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillHideNotification, object: nil)

}

func keyboardWasShown(notification: NSNotification) {
    var info: Dictionary = notification.userInfo!
    var keyboardSize: CGSize = (info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size)!
    var buttonOrigin: CGPoint = self.loginB.frame.origin;
    var buttonHeight: CGFloat = self.loginB.frame.size.height;
    var visibleRect: CGRect = self.view.frame
    visibleRect.size.height -= keyboardSize.height

    if (!CGRectContainsPoint(visibleRect, buttonOrigin)) {
        var scrollPoint: CGPoint = CGPointMake(0.0, buttonOrigin.y - visibleRect.size.height + buttonHeight + 4)
        self.scrollView.setContentOffset(scrollPoint, animated: true)

    }
    nodextext.hidden = true
    diamondPic.hidden = true
}

func hideKeyboard() {
    teamID.resignFirstResponder()   //FirstResponder's must be resigned for hiding keyboard.
    scoutID.resignFirstResponder()
    pinNum.resignFirstResponder()
    self.scrollView.setContentOffset(CGPointZero, animated: true)
    diamondPic.hidden = false
    nodextext.hidden = false
}

}

先谢谢你。

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。首先,当UI元素成为第一响应者时,您可以手动更改滚动视图的内容偏移量。您可以使用UITextFieldDelegatetextFieldDidBeginEditing:方法进行检查。尽管这经常被证明是困难的。另一件事是将所有UI元素放在表视图中,并在诸如文本字段之类的UIElement成为第一响应者时调用scrollToRowAtIndexPath:atScrollPosition:animated:

答案 1 :(得分:1)

我认为隐藏键盘的最佳方法是在scrollView委托方法中添加resignFirstResponder(或调用hideKeyboard):

  func scrollViewWillBeginDragging(scrollView: UIScrollView)

希望这有帮助