我目前正在构建一个UIScrollView
页面上有一个的应用程序,其中将有 3 个UIViews
。这三个UIViews
是leftPanel
,centerPanel
和rightPanel
。leftPanel
占屏幕宽度的30%,centerPanel
占屏幕宽度的70% ,占屏幕宽度的rightPanel
30%。默认情况下,leftPanel
和centerPanel
显示,当用户从右向左滑动leftPanel
时,从左侧rightPanel
移出,从右侧移入。中央面板从右侧移到左侧。所以leftPanel
,centerPanel
和rightPanel
都拥有相同的超级视图,也就是UIScrollView
屏幕上的。我打算在里面有一个按钮rightView
,点击后会产生一个UIImageView
在 centerPanel 出现在底部。如何控制incenterPanel
上的 from 动作?UIButton
rightPanel
我的 UIScrollView 实现使用:
self.addSubview(leftPanel)
self.addSubview(centerPanel)
self.addSubview(rightPanel)
将三个子视图添加到滚动视图。我可以使用super
关键字来获取rightPanel
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
.
请你可以建议我怎么可以参考的实例centerPanel
中UIScrollView
,从里面的代码在UIView
类的rightPanel
?
编辑:从其他视图中访问和操作视图似乎是不可取的,有什么办法可以解决这个问题吗?
视图不应直接通信。视图控制器应该协调视图之间的活动。这个视图控制器应该已经有对left
,center
和right
视图的引用。
您可以创建一个协议,以便right
视图可以通知视图控制器按钮被点击:
protocol RightViewDelegate {
func buttonWasTapped()
}
那么你RightView
可以支持这种类型的委托:
class RightView: UIView {
var delegate: RightViewDelegate?
@IBAction buttonHandler(_ sender: UIButton) {
self.delegate?.buttonWasTapped()
}
在你的ViewController
你设置委托并通过调用方法在中心视图中添加新的方法来处理委托方法中的按钮点击:
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()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句