我有一个包含三个ViewControllers的UIPageViewcontroller。一个Viewcontroller是我的ProfileViewcontroller。我的ProfileViewController中有一个按钮,按下时应告诉UIPageViewCongtroller,切换到下一个Viewcontroller。 这是我第一次实施代表,但我无法弄清楚为什么它不起作用。
UIPageViewController类:
class PageViewController: UIPageViewController, ProfileViewControllerDelegate {
private(set) lazy var orderedViewControllers: [UIViewController] = {
// The view controllers will be shown in this order
return [self.newColoredViewController("Search"),
self.newColoredViewController("Menu"),
self.newColoredViewController("Profile"),
self.newColoredViewController("Offer")]
}()
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
if orderedViewControllers.count >= 2 {
scrollToViewController(orderedViewControllers[1])
}
}
// MARK: ProfileViewControllerDelegate
func profileViewControllerDidTouchOffer(viewController:ProfileViewController, sender: AnyObject) {
scrollToNextViewController()
print("I'm pressing the offer Button")
}
ProfileViewController类:
protocol ProfileViewControllerDelegate : class {
func profileViewControllerDidTouchOffer(controller: ProfileViewController, sender: AnyObject)
}
class ProfileViewController: UIViewController {
weak var delegate: ProfileViewControllerDelegate?
@IBOutlet var profileImageView: SpringImageView!
@IBOutlet var offerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func offerButtonTouchUpInside(sender: AnyObject) {
delegate?.profileViewControllerDidTouchOffer(self, sender: sender)
}
答案
我通过改变在orderderedViewControllers中添加ViewControllers的方式更新了PageViewController类:
private(set) lazy var orderedViewControllers: [UIViewController] = {
// The view controllers will be shown in this order
let profileVC = UIStoryboard(name: "Main", bundle: nil) .instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
profileVC.delegate = self
return [self.newColoredViewController("Search"),
self.newColoredViewController("Menu"),
profileVC,
self.newColoredViewController("Offer")]
}()
答案 0 :(得分:0)
看起来您正在使用InterfaceBuilder,因此我不确定它是如何在那里完成的(可能在prepareForSegue中),但典型的模式是这样的:
let vc = ProfileViewController()
vc.delegate = self // Or whatever you want to act as the delegate
// Now show the view controller.
关键是在使用视图控制器之前,确保它的委托属性设置为委托的东西并符合协议。通常,呼叫控制器将是代表。
编辑:如果您正在使用UIPageViewController,那么您应该将该委托添加到viewController,然后再将其传递给setViewControllers https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIPageViewControllerClassReferenceClassRef/#//apple_ref/occ/instm/UIPageViewController/setViewControllers:direction:animated:completion: