我目前正在构建一个页面上带有单个 UIScrollView
的应用程序,其中将包含 3 个 UIViews
。三个 UIView
是 leftPanel
、centerPanel
和 rightPanel
。 leftPanel
占据屏幕宽度的 30%,centerPanel
占据屏幕宽度的 70%,rightPanel
占据屏幕宽度的 30%。默认显示 leftPanel
和 centerPanel
,当用户从右向左滑动时,leftPanel
从左侧移出,并且rightPanel
从右侧移入。中心面板从右侧移至左侧。因此,leftPanel
、centerPanel
和 rightPanel
都有相同的 super View ,即屏幕上的 UIScrollView
。我打算在 rightView 内有一个按钮,单击该按钮将使 centerPanel 中的 UIImageView 出现在底部。如何通过 rightPanel
中 UIButton
上的操作来控制 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 应该已经具有对 left
、center
和 right
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/