Не получается установить делегат и передать модель


#1

Здравствуйте! Помогите разобраться с проблемой

Предистория: есть контроллер (LocationViewController) с полем и кнопкой, которая открывает карту (Google Maps), после выбора местоположения контроллер с картой закрывается, и в поле появляется название места, и записывается в некую модель, передаются координаты, для того, чтобы отобразить на другом контроллере это местоположение

по коду

// LocationViewController - Окно где после выбора местоположения, через делегат передается в модель

class LocationViewController: UIViewController, MapViewControllerDelegate {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var underlinedTextField: UnderlinedTextField!

var currentPlace = Place() // в MapViewControllerDelegate

var delegate: MainInfoTableViewCellDelegate?

@objc func showMapViewController() {
    let storyboard = UIStoryboard.storyboard(storyboard: .MapsViewController)
    let viewController: MapsViewController = storyboard.instantiateViewController()
    viewController.delegate = self
    present(viewController, animated: true)
}

// метод протокола MapViewControllerDelegate, который обновляет поле
func getAddress(_ address: String?, _ geoCoordinate: CLLocationCoordinate2D?) {
    underlinedTextField.textField.text = address
    guard geoCoordinate != nil else { return }
    self.currentPlace.location = geoCoordinate
    let newPlace = Place(location: self.currentPlace.location)
    delegate?.place = newPlace.location! // через делегат передаю координаты в модель
}

карта должна отображаться в tableviewcell, поэтому координаты прередаю при ицницализации в менеджер

// MainInfoTableViewCell - ячейка с мини картой

class MainInfoTableViewCell: UITableViewCell, MainInfoTableViewCellDelegate {
    @IBOutlet weak var mapView: GMSMapView!
    
    var place: CLLocationCoordinate2D? // свойство протокола
    
    override func awakeFromNib() {
        super.awakeFromNib()
        configureMap()
    }

func configureMap() {
    MapManager.shared.setMapCamera(mapView: mapView)
    guard let place = place else { return }
    MapManager.shared.showMarker(place: place, mapView: mapView) // передаю в менеджер для отображения модель
}

// MapManager - сам менеджер
class MapManager {

static let shared = MapManager()
private init(){}
func showMarker(place: CLLocationCoordinate2D, mapView: GMSMapView) {
    print("LOCATION = \(place)")
    let marker = GMSMarker(position: place)
    marker.map = mapView
}

}

// Place - модель
import GoogleMaps
class Place {
    var location: CLLocationCoordinate2D?
    convenience init(location: CLLocationCoordinate2D?) {
        self.init()
        self.location = location
    }
}

Теперь про саму проблему, я не могу указать, кто будет делегировать MainInfoTableViewCellDelegate

по сути, свойство делегата находится в классе LocationViewController, но ситуация создания и перехода на этот контроллер следующая:

enum StepController {
    static let location: LocationViewController = UIStoryboard.storyboard(storyboard: .LocationViewController).instantiateViewController()
    static let workerKind: WorkerKindViewController = UIStoryboard.storyboard(storyboard: .WorkerKindViewController).instantiateViewController()
    ...
    static let allValues = [location, workerKind ...]
}

// NewAddViewController - контроллер, который отвечает за создания сторибордов с шагом выполнения в enum StepController
class NewAddViewController: UIViewController {

    @IBOutlet weak var segmentView: UIView!
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var stepProgress: UIProgressView!
    
    var page: Int = 0
    var stepValue: Float = 1/8
    var pagingViewController: FixedPagingViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // получаю ошибку Cannot assign value of type 'NewAddViewController' to type 'MainInfoTableViewCellDelegate?'
        // StepController.location.delegate = self 
 
        configureController()
    }
    
    func configureController() {
        configureNavigationBar()
        configureStepProgress()
        configureNextStepButton(title: "Next")
    }
    
    func configureNavigationBar() {
        navigationController?.navigationBar.barTintColor = UIColor.white
        navigationController?.navigationBar.isTranslucent = false
        navigationController?.navigationBar.shadowImage = UIImage()
        let image = UIImage(named: "close")?.withRenderingMode(.alwaysOriginal)
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(leftBarButtonAction))
        navigationItem.leftBarButtonItem?.tintColor = ColorManager.buttonColor()
    }
    
    @objc func leftBarButtonAction() {
        let storyboard = UIStoryboard(name: "CustomAlertView", bundle: nil)
        let customAlert = storyboard.instantiateViewController(withIdentifier: "CustomAlertView") as! CustomAlertView
        customAlert.providesPresentationContextTransitionStyle = true
        customAlert.definesPresentationContext = true
        customAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        customAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
        customAlert.delegate = self
        present(customAlert, animated: true, completion: nil)
    }
    
    func configureStepProgress() {
        stepProgress.trackTintColor = ColorManager.buttonBorderColor()
        stepProgress.progressTintColor = ColorManager.profileRatingColor()
        stepProgress.setProgress(stepValue, animated: false)
        stepProgress.layer.cornerRadius = CGFloat.scale(accordingToDeviceSize: 5)
        stepProgress.layer.masksToBounds = true
    }
    
    func configureNextStepButton(title: String) {
        nextButton.backgroundColor = ColorManager.buttonColor()
        nextButton.layer.cornerRadius = CGFloat.scale(accordingToDeviceSize: 14)
        nextButton.layer.masksToBounds = true
        nextButton.titleLabel!.textAlignment = .center
        let attributedString = NSMutableAttributedString(string: title)
        attributedString.addAttribute(NSAttributedStringKey.kern, value: 1.0,
                                      range: NSMakeRange(0, attributedString.length))
        attributedString.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.black], range: (title as NSString).range(of: title))
        nextButton.setAttributedTitle(attributedString, for: .normal)
        nextButton.titleLabel?.font = Font.regular.of(size: 14)
        nextButton.addShadow(color: ColorManager.buttonColor())
    }
    
    
    func showNextStep() {
        if stepProgress.progress == 1 && StepController.allValues.count == 8 {
            let storyboard = UIStoryboard.storyboard(storyboard: .PreviewJobViewController)
            let storyboardViewController: PreviewJobViewController = storyboard.instantiateViewController()
            let viewController = UINavigationController(rootViewController: storyboardViewController)
            present(viewController, animated: true)
        } else {
            page += 1
            pagingViewController.select(index: page, animated: true)
            stepValue += 1/8
            stepProgress.setProgress(stepValue, animated: true)
            if stepValue == 8/8 { configureNextStepButton(title: "Preview job") }
        }
    }
    
    @IBAction func nextButtonAction(_ sender: Any) {
        showNextStep()
    }
}