使用委托打开另一个视图控制器?

问题描述 投票:-2回答:3

我是IOS的新手,创建了一个自定义日历,如果用户选择任何日期,应用程序将重定向到另一个viewController。

我用这个链接创建了一个日历:https://github.com/Akhilendra/calenderAppiOS

我已经与代表做了,但我无法弄清楚我做错了什么。

我的代码:

protocol SelectedDateDelagate: class {
    func openAppointmentDetails()
}
class CalenderView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MonthViewDelegate {

    weak var delegate: SelectedDateDelagate?
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell=collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor=Colors.darkRed
        let lbl = cell?.subviews[1] as! UILabel
        lbl.textColor=UIColor.yellow

        let calcDate = indexPath.row-firstWeekDayOfMonth+2

        print("u selected date",calcDate,monthName)

        delegate?.openAppointmentDetails()
    }
}


class ViewController: UIViewController,SelectedDateDelagate {
    func openAppointmentDetails() {

        let myVC = storyboard?.instantiateViewController(withIdentifier: "appointmentDetailsVC") as! AppointmentDetailsViewController

        navigationController?.pushViewController(myVC, animated: true)

    }
}

现在的问题是,当我点击日期时,什么都不会发生。

ios swift
3个回答
0
投票

在这种情况下最好使用故事板,然后控制 - 将集合视图拖到第二个视图控制器。由于除了呈现视图控制器之外,您不使用您的委托进行任何其他操作,因此您可以放弃它。


0
投票

代表在其他情况下使用。在这种情况下,没有必要。此外,您不需要将UIView符合Delegates和DataSource,因为它与MVC相矛盾。相反,将日历视图(集合视图)放在UIViewController中并使该控制器符合实现方法。

你应该做这个:

class CalenderViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

var calenderView: UICollectionView!

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)!
    cell.backgroundColor = Colors.darkRed
    let lbl = cell.subviews[1] as! UILabel
    lbl.textColor = UIColor.yellow

    let calcDate = indexPath.row - firstWeekDayOfMonth + 2

    openAppointmentDetails()
}

func openAppointmentDetails() {
    let appointmentVC = storyboard?.instantiateViewController(withIdentifier: "appointmentDetailsVC") as! AppointmentDetailsViewController
    navigationController?.pushViewController(appointmentVC, animated: true)
}
}

0
投票

我解决了这个问题我忘了在ViewController的viewDidLoad()方法中添加calenderView.delegate = self

以及openAppointmentDetails()中的更改

这是变化。

class ViewController: UIViewController,SelectedDateDelagate {
func openAppointmentDetails() {

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "appointmentDetailsVC") as! AppointmentDetailsViewController
    self.present(nextViewController, animated:true, completion:nil)

}

override func viewDidLoad() {
   calenderView.delegate = self
}

}

© www.soinside.com 2019 - 2024. All rights reserved.