ios - 如何从具有相同父级的其他 UIView 控制/引用 UIView?

标签 ios swift uiview swift3 uiviewcontroller

我目前正在构建一个页面上带有单个 UIScrollView 的应用程序,其中将包含 3 个 UIViews。三个 UIViewleftPanelcenterPanelrightPanelleftPanel 占据屏幕宽度的 30%,centerPanel 占据屏幕宽度的 70%,rightPanel 占据屏幕宽度的 30%。默认显示 leftPanelcenterPanel,当用户从右向左滑动时,leftPanel 从左侧移出,并且rightPanel 从右侧移入。中心面板从右侧移至左侧。因此,leftPanelcenterPanelrightPanel 都有相同的 super View ,即屏幕上的 UIScrollView。我打算在 rightView 内有一个按钮,单击该按钮将使 centerPanel 中的 UIImageView 出现在底部。如何通过 rightPanelUIButton 上的操作来控制 centerPanel

我的 UIScrollView 实现使用:

self.addSubview(leftPanel)
self.addSubview(centerPanel)
self.addSubview(rightPanel)

将三个 subview 添加到scrollView中。 我可以使用 super 关键字来获取 rightPanel 的 super View UIScrollView,但是如何从那里访问 centerPanel 呢? 如果我可以将对 UIView 的引用保存在名为 centerPanelAccess 的变量中,我打算执行以下操作:

var centerPanelAccess = /* link to the centerPanel */
var imageView = /* The UIImageView to add */
centerPanelAccess.addSubview(imageView)

这是我迄今为止尝试做的事情:

centerPanel.addSubView(imageView) /* Error: Instance member 'addSubview' cannot be used on type 'UIView'; did you mean to use a value of this type instead?*/

从上面来看,我认为我需要引用我的代码正在使用的 centerPanel 的特定实例,所以我尝试了这个,以专门引用该实例:

super.centerPanel.addSubView(imageView) /* Value of type 'UIView' has no member centerPanel */

通过这次尝试,我意识到 UIScrollView 中没有任何变量实际上允许我引用 centerPanel

请您建议我如何从 UIView 的代码内部引用 UIScrollView 中的 centerPanel 实例> rightPanel 类?

编辑:似乎不建议从其他 View 中访问和操作 View ,有什么办法可以解决这个问题吗?

最佳答案

View 不应直接通信。 View Controller 应该协调 View 之间的事件。此 View Controller 应该已经具有对 leftcenterright View 的引用。

您可以创建一个协议(protocol),以便 View 可以通知 View Controller 该按钮已被点击:

protocol RightViewDelegate {
    func buttonWasTapped()
}

那么您的 RightView 就可以支持这种类型的委托(delegate):

class RightView: UIView {

     var delegate: RightViewDelegate?

     @IBAction buttonHandler(_ sender: UIButton) {
         self.delegate?.buttonWasTapped()
}

在您的 ViewController 中,您设置委托(delegate)并通过调用在中心 View 中添加新内容的方法来处理委托(delegate)方法中的按钮点击:

class ViewController: UIViewController, RightViewDelegate {

    var leftView: LeftView!
    var rightView: RightView!
    var centerView: CenterView!

    func viewDidLoad {
        super.viewDidLoad()

     // After you set your views into your scroll view:
        self.rightView.delegate = self
    }


    func buttonWasTapped() {
        self.centerView.addView()
    }
}

关于ios - 如何从具有相同父级的其他 UIView 控制/引用 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278288/

相关文章:

ios - 在 iOS 5.0 模拟器中使用 UIManagedDocument 时出现 NSFileCoordinator 错误

iOS - Facebook pop 框架 - 永远重复 "shake"动画

Json 解析 Swift 3 Alamofire

ios - 如何判断UIView是否已经加载

ios - 核心数据更改是否反射(reflect)在本地 NSManagedObject 子类变量中?

objective-c - 滚动到底部时向 UITableView 添加行

ios - View 不在屏幕时的 UIView 动画 alpha 不起作用

ios - UIImageView 不会调整大小以匹配 UIView 的框架

swift - stringByEvaluatingJavaScriptFromString

ios - 动态调整 UICollectionView 大小以确保没有项目间间距