To use a UIView or UIViewController for timer obje

2019-08-11 06:42发布

问题:

I've got a UI with several elements, some of which I'd like to encapsulate into their own objects. For example, one object would be a timer (basically just a UILabel sitting in a UIView) with the externally-available members:

  • startTime (property)
  • start and pause (methods)

(And also a im_done NSNotification when the timer reaches 0.) This object and several others would be used together in a single UIViewController.

Would a UIView or UIViewController be more appropriate to subclass for the timer object (and all the others)? Reading this answer leads me to believe UIView, but for my specific case (especially for the more complicated objects), I'm not sure. Thanks for reading.

EDIT: Just to clarify, I would want all code that implements timer functionality separate from my main view controller. One big reason is so that the timer object would be portable.

回答1:

You should have a subclass of UIView, but it should just have the view components to display whatever time information you need. You should also have a MyTimer class which encapsulates the timing functionality and provides callbacks on changes (such as the time remaining and perhaps the completion as a separate when the time remaining reaches zero). Ideally the callbacks pass the MyTimer and, as a convenience, the remaining time value so you don't need to use the accessor method in the simple use case).

Now, you already have a view controller which is managing your broader view, and it can create add your UIView subclass to the main view and create, own and manage the associated MyTimer instances which drive those views.



回答2:

This I think comes down to preference. You'll include a uiview and uiviewcontroller in a parent view controller differently and this difference can make a uiviewcontroller more difficult if you don't understand containers. I would say best practice would be in a uiviewcontroller but it really is up to you.