Objective C View to Controller Communication

后端 未结 5 985
滥情空心
滥情空心 2021-01-29 04:54

What is the proper way to accept user input in a view and then transfer it to that view\'s controller? I know the NotificationCenter is one option, but surely there is a more el

5条回答
  •  星月不相逢
    2021-01-29 05:15

    Use the delegate protocol design pattern, or target-action by subclassing UIControl. Think about how a UIButton tells a view controller that it's been pressed. In interface builder, you connect an action - a selector something like touchUpInside: to a target - the view controller that owns it. In non-IB, you directly tell the UIButton what selector and what target to use.

    Both methods make sense in different cases. For a UITextField, for example, it makes more sense to use delegation because it's possible for the text field to send you any number of events, such as an event when the user begins editing, ends editing, or types a character.

    For a button, it makes more sense to use target-action because there's really only one event expressed in different forms.

    For swipes and drags and other gestures, use UIGestureRecognizers.

提交回复
热议问题