gpt4 book ai didi

ios - 从另一个类(class) swift 获得 IBOutlet

转载 作者:搜寻专家 更新时间:2023-11-01 06:19:42 45 4
gpt4 key购买 nike

我在 Main_Screen 类中有一个 IBOutlet,它在连接到具有 ScrollView 的主 ViewController 的类中可用,但如果我尝试获取它,则返回 nil

View Controller 中的代码

import UIKit

class ViewController: UIViewController , UIScrollViewDelegate {

@IBOutlet weak var scrollVieww: UIScrollView!

override func viewDidLoad() {
super.viewDidLoad()

self.scrollVieww.pagingEnabled = true
self.scrollVieww.delegate = self

let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewControllerWithIdentifier("MainScreen") as? Main_Screen {
// imageview returns nil :(
let imageView = vc.avatarImageView
}

// Do any additional setup after loading the view, typically from a nib.
let V1 = self.storyboard?.instantiateViewControllerWithIdentifier("HomeScreen") as UIViewController!
//Add initialized view to main view and its scroll view and also set bounds
self.addChildViewController(V1)
self.scrollVieww.addSubview(V1.view)
V1.didMoveToParentViewController(self)
V1.view.frame = scrollVieww.bounds

//Initialize using Unique ID for the View
let V2 = self.storyboard?.instantiateViewControllerWithIdentifier("MainScreen") as UIViewController!
//Add initialized view to main view and its scroll view also set bounds
self.addChildViewController(V2)
self.scrollVieww.addSubview(V2.view)
V2.didMoveToParentViewController(self)
V2.view.frame = scrollVieww.bounds

//Create frame for the view and define its urigin point with respect to View 1
var V2Frame: CGRect = V2.view.frame
V2Frame.origin.x = self.view.frame.width
V2.view.frame = V2Frame

//The width is set here as we are dealing with Horizontal Scroll
//The Width is x3 as there are 3 sub views in all
self.scrollVieww.contentSize = CGSizeMake((self.view.frame.width) * 2, (self.view.frame.height))

}

最佳答案

简短回答:不要那样做。您应该将另一个 View Controller 的 View 视为私有(private) View 。

如果您需要操作另一个 View Controller 的 UI,请添加用于请求 UI 更改的公共(public)方法,然后让 VC 中的代码进行更改。

这都是更好的设计,并且它避免了其他 View Controller 的 View 尚未创建的情况,因此它们为 nil 并且它失败/崩溃并显示“在尝试展开可选时遇到 nil”消息。

关于ios - 从另一个类(class) swift 获得 IBOutlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36343111/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com