我有一个storyviewcontroller,它的视图上有对象。我需要更改UILabel(在storyviewcontroller中)上的文本,并将视图加载到数组上。我已将IBOutlet连接到storyviewcontroller中的标签。
class StoryViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var inspiredButton: UIButton!
我已经创建了storyviewcontroller类的对象,并且能够访问其变量。但是,在创建storyviewcontroller的对象之后,IBOutlet为nil。因此,我得到一个异常,说解包时发现nil
let story:StoryViewController = StoryViewController() story.textLabel.text = sampleText()
您能帮我这个忙吗?这是整个项目的链接 https://github.com/abhishekagarwal2301/DTC 谢谢
IBOutlet在视图加载过程中初始化,在您尝试到达它们时无法访问它们。相反,您必须向您的viewcontroller声明一个字符串变量,并在其viewDidLoad方法上设置要标记的文本(在加载过程完成之后)
class StoryViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var inspiredButton: UIButton! var text:String! override func viewDidLoad() { super.viewDidLoad() textLabel.text = text } }
然后从第一个控制器初始化文本变量,如下所示
let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil) var story = storyboard.instantiateViewControllerWithIdentifier("YourVCIdentifier") as StoryViewController story.text = sampleText() self.presentViewController(story, animated: false , completion: nil)