菜鸟教程小白 发表于 2022-12-12 19:19:45

objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件


                                            <p><p>我想知道如何以编程方式将 UI 元素添加到现有的 nib 文件中。</p>

<p>如果我在 <code>loadView</code> 方法中以编程方式创建 View 并添加如下代码,则标签会正确显示。 </p>

<pre><code>self.view = [ initWithFrame:.applicationFrame];

UILabel *lbl = [ initWithFrame:CGRectMake(0,2,150,100)];

;
</code></pre>

<p>但是如何将标签添加到现有的 nib 文件中?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>正如 Paul.s 指出的,您需要在 <code>viewDidLoad</code> 方法中执行您的自定义代码。</p>

<p>来自 Apple 文档。</p>

<blockquote>
<p>This method is called after the view controller has loaded its
associated views into memory. This method is called regardless of
whether the views were stored in a nib file or created
programmatically in the loadView method. This method is most commonly
used to perform additional initialization steps on views that are
loaded from nib files.</p>
</blockquote>

<p>所以,在你的 Controller 中你可以这样做:</p>

<pre><code>- (void)viewDidLoad
{
   ;

   // your other views here

   // call addSubview method on self.view
}
</code></pre>

<p>你为什么这样做?因为在这里您可以确定 View 已加载到内存中并且 socket 已正确设置。</p>

<p>相反,关于<code>loadView</code>方法</p>

<blockquote>
<p>If you override this method in order to create your views manually,
you should do so and assign the root view of your hierarchy to the
view property. (The views you create should be unique instances and
should not be shared with any other view controller object.) Your
custom implementation of this method should not call super.</p>
</blockquote>

<p>一个例子可以是:</p>

<pre><code>- (void)loadView
{
    CGRect applicationFrame = [ applicationFrame];
    UIView *contentView = [ initWithFrame:applicationFrame];
    contentView.backgroundColor = ;

    self.view = contentView;

    // call addSubview method on self.view
}
</code></pre>

<p>我建议你阅读<a href="https://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW1" rel="noreferrer noopener nofollow">View Controller Programming Guide for iOS</a> .</p>

<p>希望对你有帮助。</p></p>
                                   
                                                <p style="font-size: 20px;">关于objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/9175407/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/9175407/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件