如何使用以编程方式创建的uitextfield隐藏键盘

时间:2014-08-14 20:53:59

标签: swift ios8 xcode6

我已经以编程方式创建了一个名为" myTextField"的uitextfield。在" viewDidLoad"。

当我创建一个功能来在用户点击屏幕上的任何位置时隐藏键盘," myTextField"没有被xcode识别。是因为文本字段是在" viewDidLoad"中创建的? 有没有办法访问和使用" myTextField"在外面" viewDidLoad"?

更新:我终于有机会回家并复制我的代码以显示我的意思。这是我的代码:

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Prepare keyboard notifications
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardDidHideNotification, object: nil);


    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width;
    let screenHeight = screenSize.height;
    let myTextView : UITextField = UITextField(
        frame : CGRect(x:10, y:(screenHeight/2), width:(screenWidth-20), height: (screenHeight/3) ) )
    myTextView.backgroundColor = UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )
        self.scrollView.addSubview( myTextView )
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
// Call this method somewhere in your view controller setup code.

func keyboardWillShow(sender: NSNotification) {
    let dict:NSDictionary = sender.userInfo as NSDictionary
    let s:NSValue = dict.valueForKey(UIKeyboardFrameEndUserInfoKey) as NSValue;
    let rect :CGRect = s.CGRectValue();
    self.scrollView.contentOffset = CGPoint(x: 0, y: rect.height)

}
   func keyboardWillHide(sender: NSNotification) {

   let dict:NSDictionary = sender.userInfo as NSDictionary
   let s:NSValue = dict.valueForKey(UIKeyboardFrameBeginUserInfoKey) as NSValue;
  let rect :CGRect = s.CGRectValue();
  self.scrollView.contentOffset = CGPoint(x: 0, y: 0)

 }

我已经以编程方式创建了一个UITextView,因为我在Xcode 6中挣扎于自动布局。与此同时,我已经更新到Xcode beta 5(从4开始),现在甚至我的scrollview都在表演奇怪的。所以也许我必须用代码创建它。

如何在viewDidLoad函数之外访问我的textview?

2 个答案:

答案 0 :(得分:0)

将其声明为该类的属性,然后您可以从任何地方访问它。否则,其范围仅限于viewDidLoad函数,您无法从外部访问它。

class YourClass {

    var myTextField:UITextField

    override func viewDidLoad() {
        //init myTextField
    }  

    func test() {
       //do something with myTextField
    }
}      

答案 1 :(得分:0)

使用此功能解除键盘: -

python-protobuf