iphone - 如何以编程方式创建 iOS 应用程序 View

标签 iphone ios objective-c uiview uiviewcontroller

我正在编写一个应用程序,但没有使用 Storyboard/xib 来创建 View ,并且不确定放置 View 设置代码的最佳位置。我尝试了几种不同的方法,但我不确定将 View 设置代码与 Controller 代码分开的最佳方法。

到目前为止我尝试过的方法是:

  1. 将我的所有 View 设置代码(创建和定位按钮/标签)等放入 Controller viewDidLoad 方法中。我很确定这是一种糟糕的做法,因为您最终会在 Controller 中包含大量代码。

  2. 子类化 UIView 并在 initWithFrame 方法内设置界面元素。然后,我可以将此 View 添加到我的 View Controller View 之上。

    _customView = [[CustomView alloc] initWithFrame:self.view.frame];
    _customView.customLabel.text = @"Foo";
    [self.view addSubView:_customView]
    

或者我将 Controller View 指定为我的customView

_customView = [[CustomView alloc] initWithFrame:self.view.frame];
self.view = _customView;
_customView.customLabel.text = @"Foo";

虽然试图尽可能保持这个问题的非主观性,但是否有以编程方式创建 iOS 界面的最佳实践?这两种方法中的任何一种都是保持 View 代码和 Controller 代码分离且可重用的好方法吗?

最佳答案

如果您只需要使用该 View 一次,请将代码保留在 viewDidLoad 方法中。也许您可以移动 Controller 中特定方法中创建 View 所需的代码。

- (void)viewDidLoad
{
    [super viewDidLoad];

    // other code here...
    [self createView];
}

此外,如果您的 View 将是 Controller 的view,您还可以考虑重写loadView方法并将代码放在那里。来自苹果文档。

You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property.

如果您需要多次实例化 View ,我将继承 UIView 并使用委托(delegate)模式与您的 Controller 进行通信。

如果您选择此方法,则需要重写 layoutSubviews 方法以在 View 中排列子项。

一个明显的例子可以在 How To Make a Custom UIView in iOS 5: A 5 Star Rating View 中找到。 .

关于iphone - 如何以编程方式创建 iOS 应用程序 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15746257/

相关文章:

iphone - 如果我的配置文件过期,应用程序还能继续运行吗?

android - 有什么办法可以在 android 和 i-os 的钛合金应用程序中使用 sqlite 数据库吗?

ios - UITableViewCell 图片从 URL 下载

objective-c - 如何检查 C 数组中的空字符串

iphone - NSArray 传递时变成 NSCFArray

ios - 适用于 iOS 的 Facebook Photo Picker Controller(类似于 Places Picker Controller )

iphone - NSInvalidArgumentException',原因: '-[__NSPlaceholderDictionary initWithObjects:forKeys: error

iphone - 从 AVCaptureAudioDataOutputSampleBufferDelegate 播放音频

html - Iphone 7 Safari 文本跳转问题

ios - 无法安装苹果 watch 应用程序