c# - InstantiateViewController 调用 ViewDidLoad
<p><p>我有一个经典的主从逻辑并尝试在单击事件中使用 InstantiateViewController 创建详细 UIViewController 的实例。</p>
<p>这是我的代码,</p>
<p><strong>MasterViewController.cs</strong></p>
<pre><code>detailButton += delegate {
UIStoryboard Storyboard = UIStoryboard.FromName ("Main", null);
Console.WriteLine("InstantiateViewController() started");
var profileController = Storyboard.InstantiateViewController("ProfileController") as ProfileController;
Console.WriteLine("InstantiateViewController() ended");
profileController.Id = 5;
};
</code></pre>
<p><strong>ProfileViewController.cs</strong></p>
<pre><code>public partial class ProfileController : UIViewController
{
public int Id { get; set; }
public override void ViewDidLoad()
{
Console.WriteLine("ViewDidLoad() called");
}
}
</code></pre>
<p>当我点击按钮输出时,</p>
<pre><code>InstantiateViewController() started
ViewDidLoad() called
InstantiateViewController() ended
</code></pre>
<p>这意味着 <code>profileController.Id</code> 设置在 <code>ViewDidLoad()</code> 之后,这意味着我无法在 ViewDidload 事件中按 Id 加载数据,因为 Id 为空。</p>
<p>所以我的问题是为什么<code>ViewDidLoad()</code>会被InstantiateViewController()调用,我应该在哪个方法中按Id加载数据?</p>
<p>谢谢。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p><code>VoewDidLoad</code> 是 <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/viewDidLoad" rel="noreferrer noopener nofollow">called</a> <code>ViewController</code> 加载到内存时。</p>
<p>因此,获取数据的正确位置是 <code>ViewDidAppear</code>。
<code>ViewDidAppear</code> 通知 <code>ViewController</code> 它的 View 已添加到 View 层次结构中。</p>
<p>更新:</p>
<p>根据评论中提供的新信息,您可以执行以下操作:</p>
<pre><code>public partial class ProfileController : UIViewController
{
private int _id;
public void SetupProfile (int id)
{
// Save the Id if necessary.
_id = id;
// Add event with this id related.
}
public override void ViewDidLoad()
{
Console.WriteLine("ViewDidLoad() called");
}
}
</code></pre>
<p>如果您仍想在 <code>ViewDidAppear</code> 中进行事件设置,则可以将这种方法与事件一起使用:</p>
<pre><code>yourClass.Event -= MyHandler;
yourClass.Event += MyHandler;
</code></pre></p>
<p style="font-size: 20px;">关于c# - InstantiateViewController 调用 ViewDidLoad,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/37779245/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/37779245/
</a>
</p>
页:
[1]