我正在尝试制作一个函数,该函数接收View Controller的名称(字符串),然后以模态形式显示该View Controller。示例:
func presentViewControllerModally(newViewControllerName: String){
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "\(newViewControllerName)_Identifier") as! newViewControllerName
self.present(newViewController, animated: false, completion: nil)
}
但是我无法使as! newViewControllerName
像newViewControllerName
的类型一样工作,而不是对象本身。
答案 0 :(得分:3)
您不必将控制器转换为自定义子类。您可以只显示UIViewController
。
答案 1 :(得分:1)
如果必须返回真正的viewController类型,只需使用泛型即可。
R *r;
void on_recv(struct bufferevent *bev, void *arg)
{
struct evbuffer *src;
size_t len;
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
......
BaseHandler *handler = r->get_handler();
char data[MAX_BUFSIZE] = { 0 };
char new_data[MAX_BUFSIZE] = { 0 };
evbuffer_copyout(src, data, len);
LOGE("recv len1: %d\n", len);
if (handler->handle(data, new_data)) {
LOGE("recv len2: %d\n", len);
}
......
}
然后打电话
func presentViewControllerModally<T: UIViewController>(newViewControllerName: String) -> T? {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if let newViewController = storyBoard.instantiateViewController(withIdentifier: "\(newViewControllerName)_Identifier") as? T {
self.present(newViewController, animated: false, completion: nil)
return newViewController
}
return nil
}
如果您不需要正确的类型,而只是UIViewController,则不需要强制转换。