2015-07-16 2 views
2

Я пытаюсь представить вид конфигурации листа (AddSoundEffect) для моего главного окна/контроллера представления (я использую раскадровки), а когда диспетчер просмотра конфигурации отклонен, введите значения, введенные в вид AddSoundEffect, и передайте это обратно к основному виду. Мой текущий код в главном контроллере представления:Добавить обработчик завершения в presentViewControllerAsSheet (NSViewController)?

presentViewControllerAsSheet(self.storyboard!.instantiateControllerWithIdentifier("AddSoundEffect") as! AddSoundViewController 

И в файле AddSoundViewController.swift, код, чтобы закрыть это:

self.dismissViewController(self) 

Чтобы передать данные, у меня есть класс-независимый кортеж, который я сохранить данные в. Как добавить обработчик завершения в presentViewControllerAsSheet и (опционально) есть ли лучший способ передать данные между контроллерами представлений?

Установка: Xcode версии 6.4, OS X 10.10.4

ответ

4

Delegation модель является самым простым способом для вас.

// Replace this with your tuple or whatever data represents your sound effect 
struct SoundEffect {} 

protocol AddSoundViewControllerDelegate: class { 
    func soundViewController(controller: AddSoundViewController, didAddSoundEffect: SoundEffect) 
} 

// 
// Let's say this controller is a modal view controller for adding new sound effects 
// 
class AddSoundViewController: UIViewController { 
    weak var delegate: AddSoundViewControllerDelegate? 

    func done(sender: AnyObject) { 
    // Dummy sound effect info, replace it with your own data 
    let soundEffect = SoundEffect() 

    // 
    // Call it whenever you would like to inform presenting view controller 
    // about added sound effect (in case of Done, Add, ... button tapped, do not call it 
    // when user taps on Cancel to just dismiss AddSoundViewController) 
    // 
    self.delegate?.soundViewController(self, didAddSoundEffect: soundEffect) 

    // Dismiss self 
    self.dismissViewControllerAnimated(true, completion: {}) 
    } 
} 

// 
// Let's say this controller is main view controller, which contains list of all sound effects, 
// with button to add new sound effect via AddSoundViewController 
// 
class SoundEffectsViewController: UIViewController, AddSoundViewControllerDelegate { 
    func presentAddSoundEffectController(sender: AnyObject) { 
    if let addSoundController = self.storyboard?.instantiateViewControllerWithIdentifier("AddSoundEffect") as? AddSoundViewController { 
     addSoundController.delegate = self 
     self.presentViewController(addSoundController, animated: true, completion: {}) 
    } 
    } 

    func soundViewController(controller: AddSoundViewController, didAddSoundEffect: SoundEffect) { 
    // This method is called only when new sound effect is added 
    } 
} 

Другой способ заключается в использовании закрытия:

// Replace this with your tuple or whatever data represents your sound effect 
struct SoundEffect {} 

// 
// Let's say this controller is a modal view controller for adding new sound effects 
// 
class AddSoundViewController: UIViewController { 
    var completionHandler: ((SoundEffect) ->())? 

    func done(sender: AnyObject) { 
    // Dummy sound effect info, replace it with your own data 
    let soundEffect = SoundEffect() 

    // 
    // Call it whenever you would like to inform presenting view controller 
    // about added sound effect (in case of Done, Add, ... button tapped, do not call it 
    // when user taps on Cancel to just dismiss AddSoundViewController) 
    // 
    self.completionHandler?(soundEffect) 

    // Dismiss self 
    self.dismissViewControllerAnimated(true, completion: {}) 
    } 
} 

// 
// Let's say this controller is main view controller, which contains list of all sound effects, 
// with button to add new sound effect via AddSoundViewController 
// 
class SoundEffectsViewController: UIViewController { 
    func presentAddSoundEffectController(sender: AnyObject) { 
    if let addSoundController = self.storyboard?.instantiateViewControllerWithIdentifier("AddSoundEffect") as? AddSoundViewController { 
     addSoundController.completionHandler = { [weak self] (soundEffect) ->() in 
     // Called when new sound effect is added 
     } 
     self.presentViewController(addSoundController, animated: true, completion: {}) 
    } 
    } 
} 

Или много других способов, как отправка уведомлений, ... что подходит вашим потребностям. Но шаблон делегирования или закрытия - лучший способ пойти в этом конкретном случае.


Я пропустил, что ваш вопрос о NSViewController. Этот пример для iOS, но тот же шаблон можно использовать на OS X без каких-либо проблем.

+0

Я работаю с 'NSViewController's, не' UIViewController's. Будет ли это работать одинаково? – Matt

+0

Да, без каких-либо проблем. Это общие шаблоны, используемые как для iOS, так и для OS X. – robertvojta

3

Самый простой способ обнаружения открытия или закрытия листа является использование Sheet Notifications:

class ViewController: NSViewController, NSWindowDelegate { 

    override func viewDidLoad(){ 
     NSApplication.sharedApplication().windows.first?.delegate = self 
    } 
    func windowDidEndSheet(notification: NSNotification) { 

    } 
    func windowWillBeginSheet(notification: NSNotification) { 

    } 
} 
Смежные вопросы