无法调用UIViewController非静态方法问题求助(C# iOS跨平台开发)
Hey there, let's work through why you can't call SetLink() on your WebViewController instance! The core issue here is a type casting mistake, plus a small timing problem with your web view initialization. Let's break this down step by step.
1. 核心问题:类型转换错误
Right now, you're casting the instantiated view controller to the base UIViewController type:
UIViewController ctrl = (UIViewController)board.InstantiateViewController("WebViewController");
Since the compiler only sees ctrl as a UIViewController, it doesn't know about the SetLink() method you defined in your WebViewController subclass. That's why you can't access it.
修复方法:转换为子类类型
Change the cast to WebViewController instead, so the compiler recognizes the subclass's methods:
public static void OpenWebPage(string link, UIViewController controller) { UIStoryboard board = UIStoryboard.FromName("Main", null); // 转换为WebViewController类型,而非基类UIViewController WebViewController ctrl = (WebViewController)board.InstantiateViewController("WebViewController"); // 现在可以直接调用SetLink()了 ctrl.SetLink(link); ctrl.ModalTransitionStyle = UIModalTransitionStyle.PartialCurl; controller.PresentViewController(ctrl, true, null); }
2. 额外优化:解决WebViewer初始化时机问题
Even after fixing the cast, you might still run into a problem: when you call SetLink() in OpenWebPage, the WebViewer hasn't been initialized yet. ViewDidLoad() runs after you present the view controller, so WebViewer will be null when SetLink() is first called.
修复方法:存储链接并在ViewDidLoad中加载
Update your WebViewController to store the target link temporarily, then load it once the web view is ready:
public partial class WebViewController : UIViewController { WKWebView WebViewer; // 新增字段存储目标链接 private string _targetLink; public WebViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); WebViewer = new WKWebView(View.Frame, new WebKit.WKWebViewConfiguration()); WebViewer.SizeToFit(); // 优先使用传入的链接,没有则用默认链接 string loadUrl = string.IsNullOrEmpty(_targetLink) ? "https://www.360bsoft.com/register" : _targetLink; WebViewer.LoadRequest(Foundation.NSUrlRequest.FromUrl(Foundation.NSUrl.FromString(loadUrl))); WebViewerContainer.AddSubview(WebViewer); } public void SetLink(string link) { _targetLink = link; // 如果WebViewer已经初始化,直接加载新链接 if(WebViewer != null) { WebViewer.LoadRequest(Foundation.NSUrlRequest.FromUrl(Foundation.NSUrl.FromString(link))); } } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } }
3. 最后检查点
Make sure these Storyboard settings are correct to avoid instantiation issues:
- Select your
WebViewControllerin Storyboard, go to the Identity Inspector - Confirm the Custom Class is set to
BSoft.iOS.WebViewController(full namespace included) - Confirm the Storyboard ID is exactly
WebViewController(matches what you pass toInstantiateViewController)
内容的提问来源于stack exchange,提问作者Darius Buhai

