2016-02-14 52 views
0

我以編程方式創建了一個文本視圖,並且在viewdidload之外有一個外部函數,我想在其中更改該文本視圖的內容。我如何實現這一目標?這裏是我正在使用的代碼 就像事情一樣。我目前收到這個錯誤「Value of type'UIView'has no member'textView''on line
self.view.textView.text =」Yo Dawg !!「如何從一個calss成員函數訪問編程創建的UI對象

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 

回答

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 

} 
+0

Paulw11我明白你的推理,但這是行不通的。我得到這個錯誤「類型rootViewController的成員沒有成員myTextView」上面Seto提供的解決方案,但是,作品 –

+0

檢查你的輸入。 – Paulw11

+0

IIRC,你不需要用'self.'來快速調用變量。因此,不用調用'self.myTextView.text =',你可以簡單地寫'myTextView.text ='。 –

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!!" 
    } 
} 
+0

謝謝,這個作品! :) –

相關問題