MVC 和 UI 按钮
我正在开发一个 iPad 项目,该项目动态创建许多我需要添加到应用程序主视图中的按钮。我正计划从我的 ViewController 中触发一个位于我的 View 内部的方法...假设它称为 add_buttons。我的印象是,在 MVC 模式中,视图应该处理按钮和一般显示的渲染,但控制器应该处理交互。我还认为,让视图“了解”视图控制器是一个糟糕的设计。
所以我想我的问题是,我应该将按钮点击逻辑包含在我的控制器中吗?如果是这样,我该如何处理分离?如果我在视图中创建按钮,那么它必须具有对视图控制器的引用才能用作事件处理程序的委托。如果我在控制器中创建它们,那么我觉得我需要在控制器中设置某些 UI 元素,这对我来说似乎是错误的。我知道我错过了一些明显的东西,但到目前为止的搜索已被证明是徒劳的。
有人能指出我正确的方向吗?
I have an iPad project I'm working on that dynamically creates a number of buttons that I need to add to the main view of my application. I was planning on firing a method that lives inside my View from my ViewController...say it's called add_buttons. It's my impression that in the MVC pattern, the view should handle the rendering of buttons and the general display, but the controller should handle the interaction. I'm also under the impression that it's bad design for the view to "know" about the view controller.
So I guess my question is, should I have my button tap logic contained in my controller? If so, how do I handle the separation? If I'm creating the buttons in my view, then it would have to have a reference to the view controller to use as the delegate for the event handler. If I create them in the controller, then I feel like I need to set certain UI elements in the controller which seems wrong to me. I know I'm missing something obvious but searching so far has proven fruitless.
Can anyone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
按钮点击逻辑肯定属于控制器。
创建按钮的代码可能也属于控制器。但是,包含一个视图方法是有意义的,该方法返回一个已配置其外观但未配置其行为的按钮。
一些一般性的观点:
另外,方法的命名约定采用小驼峰命名法。例如:
add_button
应该是addButton
。The button tap logic most certainly belongs in the controller.
The code that creates the buttons probably belongs in the controller too. However, it would make sense to include a view method that returns a button with its appearance configured but not its behaviour.
Some general pointe:
Also, the naming convention for methods lowerCamelCase. Eg:
add_button
should beaddButton
.当您添加按钮到视图时,
在视图控制器中添加
target:nil 事件将由包含此视图的第一个控制器处理
when you add button to view,
in view controller add
with target:nil event will be handled by first controller containing this view
我最近完成了一个项目,其中我必须动态创建包含 UITextfields 和 UILabels 的 UIViews。我解决这个问题的方法是从视图控制器中调用“addViews”函数。我认为这是一种更好、更简单的方法,而不是从 UIView 内部处理视图控制器。我已经测试了我的方法并且工作完全正常(动态更改 UIView 大小并使用 UITextfield 和 UILabel 添加其他 UIView)。
I rescently finished a project where I had to dynamically create UIViews which contained both UITextfields and UILabels.My approach to this problem was to call the "addViews" function from within the view controller. I figured this to be a better and easier approach rather than dealing with view controllers from inside the UIView. I have tested my approach and works completely fine (dynamically change UIView size and adding other UIViews with a UITextfield and a UILabel).