Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在viewController中调用扩展函数_Ios_Iphone_Swift - Fatal编程技术网

Ios 如何在viewController中调用扩展函数

Ios 如何在viewController中调用扩展函数,ios,iphone,swift,Ios,Iphone,Swift,扩展中的func1无法访问viewController中的func2。有没有办法让这成为可能 func func2() { // do something } } //<-- View controller ends here extension UIViewController { func func1(){ func2() } func func2(){ //做点什么 } }//您不能在逻辑扩展的UIViewController中使用UIViewControl

扩展中的func1无法访问viewController中的func2。有没有办法让这成为可能

func func2() {
   // do something
}

}  //<-- View controller ends here

extension UIViewController {


func func1(){
    func2()
}
func func2(){
//做点什么
}

}//您不能在逻辑扩展的
UIViewController
中使用
UIViewController
子类的方法。由于
func2
是自定义视图控制器的一种方法,因此我猜它是一个
ViewController
实例

您应该扩展
ViewController
,但不能扩展
UIViewController

但如果您的目标是扩展
UIViewController
,则不可能实现

希望能有帮助

更新:感谢@Cristik:您实际上可以通过以下方式使用扩展中的方法:

(自身作为ViewController)?.func2()

更新2:

代码如下:

请注意,
func1
将仅对您的
MyCustomViewController
起作用,因为只有
MyCustomViewController
具有该
func2
方法


很抱歉,屏幕截图的格式设置有点奇怪。

我想您可能有错误或打字错误,您正在扩展
UIViewController
而不是
ViewController
,请检查您的意思,它可以工作:

class ViewController: UIViewController {
    func func2() {
        print("I am being called")
    }
}

extension ViewController {
    func func1(){
        func2()
    }
}
用法

let vc = ViewController()
vc.func1() // Outputs "I am being called"
let vc = ViewController()
vc.func1() // Outputs "I am being called"
示例2
UIViewController
的扩展):

用法

let vc = ViewController()
vc.func1() // Outputs "I am being called"
let vc = ViewController()
vc.func1() // Outputs "I am being called"

但函数是否在同一文件中声明?都是同一个类的一部分吗?声明在同一个文件中可以从
UIViewController
(self as?ViewController)?.func2()
当您说扩展ViewController时,是指func2所在的类的名称吗?Cristik,我需要更多的详细信息,因为我是swift/ios新手,你能帮我吗explain@fredshmed确切地抱歉,我不确定那个VC的名字,所以我假设它只是
ViewController
我认为不需要创建
ViewController
的对象。您可以直接通过self调用它。@dahiya_boy使用示例2,您不能直接调用
self.func2()
UIViewController
没有这样的方法,如果有,您将看到错误
类型为“UIViewController”的值没有成员“func2”