如何从calss成员函数访问以编程方式创建的UI对象

时间:2016-02-14 00:28:26

标签: ios swift

我以编程方式创建了一个文本视图,并且我在viewdidload之外有一个外部函数,我希望在其中更改该textview的内容。我如何实现这一目标?这是我正在使用的代码 事情就是这样。我目前收到此错误"类型值' UIView'没有会员' textView' "在线上 self.view.textView.text =" Yo Dawg !!"

class rootViewController: UIViewController {
    override func viewDidLoad() {
         super.viewDidLoad()

         let myTextView = UITextView(frame: CGRectMake(0,0,100,50))
         myTextView.backgroundColor = UIColor.clearColor()
         myTextView.textColor = UIColor.whiteColor()
         myTextView.font = UIFont (name: "Helvetica Neue", size: 20)
         myTextView.textAlignment = NSTextAlignment.Center
         myTextView.text = "Hello World"

         self.view.addSubview(timerView)

    }//End view did load



    func changeText(){//This function updates the text within the textview
        self.view.textView.text = "Yo Dawg!!"
   }//End change text function

}//End rootViewController

2 个答案:

答案 0 :(得分:0)

您需要在实例变量/属性中保留对文本视图的引用,而不是在局部变量中:

class rootViewController: UIViewController {

    var myTextView:UITextView!

    override func viewDidLoad() {
         super.viewDidLoad()

         self.myTextView = UITextView(frame: CGRectMake(0,0,100,50))
         self.myTextView.backgroundColor = UIColor.clearColor()
         self.myTextView.textColor = UIColor.whiteColor()
         self.myTextView.font = UIFont (name: "Helvetica Neue", size: 20)
         self.myTextView.textAlignment = NSTextAlignment.Center
         self.myTextView.text = "Hello World"

         self.view.addSubview(timerView)

    }//End view did load



    func changeText(){//This function updates the text within the textview
        self.myTextView.text = "Yo Dawg!!"
   }//End change text function

}

答案 1 :(得分:0)

您可以为textview指定一个唯一标记,并使用它来获取参考。

override func viewDidLoad() {
     super.viewDidLoad()

     let myTextView = UITextView(frame: CGRectMake(0,0,100,50))
     myTextView.backgroundColor = UIColor.clearColor()
     myTextView.textColor = UIColor.whiteColor()
     myTextView.font = UIFont (name: "Helvetica Neue", size: 20)
     myTextView.textAlignment = NSTextAlignment.Center
     myTextView.text = "Hello World"

     myTextView.tag = 1

     self.view.addSubview(timerView)
}



func changeText(){
    if let myTextView = self.view.viewWithTag(1) as? UITextView {
        myTextView.text = "Yo Dawg!!"
    }
}