对UIButton的操作不起作用

时间:2016-10-29 00:40:14

标签: ios swift uibutton

我试图通过向教程(link)学习来理解MVVM模式,并且我无法获得我已添加到UIButton中的工作(I我正在使用Swift 3.0。我已经尝试了几个小时的调试,研究了这个帖子(@selector in swift)和其他人,我仍然卡住了。当我点击按钮时,根本没有任何反应。我尝试使用选择器的各种语法选项,我认为你在下面看到的是正确的。我认为我正在使用的协议可能会导致问题,但鉴于我对协议的经验有限,我可能完全错了。

我会把所有代码都放在这里,以防有人想把它放到Xcode中。这里涉及的操作位于我添加到UIViewController的{​​{1}}中:

showGreetingButton

我的视图模型叫做GreetingViewModel,采用协议:

class GreetingViewController : UIViewController {
  let showGreetingButton = UIButton()
  @IBOutlet weak var greetingLabel: UILabel!

  var viewModel: GreetingViewModelProtocol! {
    didSet {
      self.viewModel.greetingDidChange = { [unowned self] viewModel in
        self.greetingLabel.text = viewModel.greeting
      }
    }
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    showGreetingButton.backgroundColor = UIColor.red
    showGreetingButton.tintColor = UIColor.black
    showGreetingButton.setTitle("Show Greeting", for: .normal)

    // I add the action here:
    showGreetingButton.addTarget(self.viewModel, action: #selector(GreetingViewModel.showGreeting), for: .touchUpInside)

    showGreetingButton.translatesAutoresizingMaskIntoConstraints = false    
    view.addSubview(showGreetingButton)
    let buttonTop = NSLayoutConstraint(item: showGreetingButton, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: view, attribute: NSLayoutAttribute.topMargin, multiplier: 1.0, constant: 20)
    let buttonLeading = NSLayoutConstraint(item: showGreetingButton, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1.0, constant: 0.0)
    showGreetingButton.contentEdgeInsets = UIEdgeInsetsMake(2, 2, 2, 2)
    NSLayoutConstraint.activate([buttonTop, buttonLeading])

    let model = Person(firstName: "David", lastName: "Blaine")

    let viewModel = GreetingViewModel(person: model)

    self.viewModel = viewModel
  }
}

我的简单模型是:

protocol GreetingViewModelProtocol: class {      
  var greeting: String? { get }
  var greetingDidChange: ((GreetingViewModelProtocol) -> ())? { get set }
  init(person: Person)
  func showGreeting()
}

class GreetingViewModel : GreetingViewModelProtocol {
  let person: Person
  var greeting: String? {
    didSet {
      self.greetingDidChange?(self)
    }
  }

  var greetingDidChange: ((GreetingViewModelProtocol) -> ())?

  required init(person: Person) {
    self.person = person
  }

  @objc func showGreeting() {
    self.greeting = "Hello" + " " + self.person.firstName + " " + self.person.lastName
  }
}

真的非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在设置按钮的目标之前将这些行移动到:

let viewModel = GreetingViewModel(person: model)
self.viewModel = viewModel

目前您正在添加self.viewModel作为目标,但self.viewModelnil