我正在为我的UIScrollView添加自定义UIViews,每个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中有一个按钮,根据其内容打开不同的(可能是动态的)ViewControllers,我该如何处理这个问题?
答案 0 :(得分: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
}
}
答案 1 :(得分:1)
您可以尝试修改CustomView以接受1个参数作为UIViewController。然后,当您添加手势时,将此控制器设置为目标。
代码:
view = FollowerView(self, frame: CGRectMake(0, scrollHeight, self.view.frame.width, 62))
您的CustomView初始化:
func init(controller: UIViewController, frame: CGRect)
你的视图gestureRecognizer:
followGesture = UITapGestureRecognizer(target: controller, action: "follow:")
follow.addGestureRecognizer(followGesture)
然后在您的FollowersViewController中,您可以实现目标函数:
func follow(sender: UITapGestureRecognizer) {
// do your stuff
}