【问题标题】:How to handle navigation with dynamic views iOS Swift?如何使用动态视图 iOS Swift 处理导航?
【发布时间】:2015-09-20 10:46:28
【问题描述】:

我正在向我的 UIScrollView 添加自定义 UIView,每个 UIView 都有一个按钮,需要打开一些用户配置文件,这些配置文件必须在新的 UIViewController 中打开。但是如何使用该按钮创建和连接新控制器?

这是我的代码:

class FollowersViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!


override func viewDidLoad() {
    super.viewDidLoad()
    for  var i = 0; i < count; i++ {

        view = FollowerView(frame: CGRectMake(0, scrollHeight, self.view.frame.width, 62))

        scrollView.addSubview(view)
        scrollHeight += view.frame.height
        scrollView.contentSize.height += view.frame.height
    }



}

如果我的 CustomView 中有一个按钮根据其内容打开不同的(可能是动态的)ViewController,我该如何处理这个问题?

【问题讨论】:

  • 你能展示你的 FollowerView 实现吗?
  • 我可以,但没有意义,它工作正常,但我不知道如何处理让followGesture = UITapGestureRecognizer(target: self, action: "follow:") follow.addGestureRecognizer(followGesture)打开新窗口(ViewController)的事件

标签: ios swift uiview uiscrollview


【解决方案1】:

button 添加到您的view,并为其分配标签。根据这个标签,您可以使用 switch-case 检查哪个按钮正在调用选择器 actionForButton

override func viewDidLoad() {
    super.viewDidLoad()
    for  var i = 0; i < count; i++ {
        var view: CustomView = followers[i]
        view = FollowerView(frame: CGRectMake(0, scrollHeight, self.view.frame.width, 62))

        var button = UIButton(frame: CGRectMake(0, 0, 40, 40))        
        button.addTarget(self, action: "actionForButton", forControlEvents: .TouchUpInside)
        button.tag = i;
        view.addSubview(button)

        scrollView.addSubview(view)
        scrollHeight += view.frame.height
        scrollView.contentSize.height += view.frame.height
    }
}


func actionForButton(sender: UIButton) {

    switch (sender.tag)
    {

    case 0: //perform related task
        break

    case 1: //perform related task
        break
    }
}

【讨论】:

  • 很好的尝试,但如果动态创建视图我不知道它们的数量并且不能为所有视图创建开关状态。
  • 但是如果我可以将标签用作某些函数的参数,例如:func actionForButton(sender: UIButton) { opneVievController(sender.tag) } 我可以这样做吗?
  • 当然。假设opneVievController 是您的函数,它使用参数打开相应的视图控制器。
  • 这对我有用,但为此目的,代表可能是正确的用途。
【解决方案2】:

您可以尝试修改您的 CustomView 以接受 1 个参数作为 UIViewController。然后当您添加手势时,将此控制器设置为目标。

代码:

view = FollowerView(self, frame: CGRectMake(0, scrollHeight, self.view.frame.width, 62))

您的 CustomView 初始化:

func init(controller: UIViewController, frame: CGRect)

还有你的视图手势识别器:

followGesture = UITapGestureRecognizer(target: controller, action: "follow:") 
follow.addGestureRecognizer(followGesture)

然后在你的 FollowersViewController 中你可以实现你的目标函数:

func follow(sender: UITapGestureRecognizer) {
    // do your stuff
}

【讨论】:

  • 比你,我认为这可以按我的需要工作,所以我这样做了...这样做的目的是好的还是会产生问题?
  • 我无法回答您的问题,因为我是 iOS 新手)。也许有人可以解释这样做的危险,但我不能,抱歉)。我在需要时使用它并且它有效..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多