xcode 如何创建扩展文件并在 iOS Swift 3 的 View Controller 中调用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41907999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:45:18  来源:igfitidea点击:

How to create extension file and call it in View Controller in iOS Swift 3?

iosxcodeswift3extension-methodscategories

提问by reza_khalafi

I have made extension file like this :

我已经制作了这样的扩展文件:

import Foundation
import Swift
import UIKit

extension UIButton{
func sayHello() {
        print("Hello bro...")
    }
}  

enter image description here

在此处输入图片说明

and Then call sayHello method in view controller like this:

然后像这样在视图控制器中调用 sayHello 方法:

override func viewDidLoad() {
        super.viewDidLoad()
        sayHello()  
    }

But show this error:
enter image description here

但显示此错误:
在此处输入图片说明

I think this problem accrued because of iron importing of extension file in view controller.
Please help me.
Thank you.

我认为这个问题是由于在视图控制器中导入扩展文件而产生的。
请帮我。
谢谢你。

回答by Parth Adroja

Your implementation is wrong. You are creating extension of UIButton and calling a method on UIViewController.

你的实现是错误的。您正在创建 UIButton 的扩展并在 上调用方法UIViewController

extension UIViewController {
func sayHello() {
        print("Hello bro...")
    }
} 

If you want to create a UIButtonextension

如果你想创建一个UIButton扩展

 extension UIButton {
    func sayHello() {
            print("Hello bro...")
        }
    } 

then you will need to call it on UIButtonlike below

那么你需要UIButton像下面这样调用它

let button = UIButton()
button.sayHello()

回答by Cruz

use extension UIViewControllernot use UIButton

使用extension UIViewController不使用UIButton

below code extend UIButton so

下面的代码扩展 UIButton 所以

someButton.sayHello() is works

someButton.sayHello() 是有效的

extension UIButton {
    func sayHello() {
        print("Hello bro...")
    }
}  

if you want use in viewDidLoad()of UIViewController extend UIViewController instead UIButton

如果你想在viewDidLoad()UIViewController 中使用扩展 UIViewController 而不是 UIButton

extension UIViewController {
    func sayHello() {
        print("Hello bro...")
    }
}

it works in 'viewDidLoad'

它适用于“viewDidLoad”

this is some example extension to call alert

这是呼叫警报的一些示例扩展

ex)

前任)

extension UIViewController {
    func alert(title: String, message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.view.tintColor = .black
        let someAction = UIAlertAction(title: "Some", style: .default, handler: nil)
        //let alertController.addAction(someAction)
        alertController.addAction(someAction)
        self.present(alertController, animated: true, completion: nil)
    }
}