【问题标题】:How to create extension file and call it in View Controller in iOS Swift 3?如何在 iOS Swift 3 的 View Controller 中创建扩展文件并调用它?
【发布时间】:2017-01-28 08:59:53
【问题描述】:

我做了这样的扩展文件:

import Foundation
import Swift
import UIKit

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

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

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

但是显示这个错误:

我认为这个问题是由于在视图控制器中铁导入扩​​展文件造成的。
请帮帮我。
谢谢。

【问题讨论】:

  • 您正在扩展中创建实例方法并试图调用类方法
  • 要么您需要在func 之前添加class 关键字,要么您需要将扩展​​名从UIButton 更改为UIViewController

标签: ios xcode swift3 extension-methods categories


【解决方案1】:

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

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

如果你想创建一个UIButton 扩展

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

那么您需要像下面这样在UIButton 上调用它

let button = UIButton()
button.sayHello()

【讨论】:

  • @LeoDabus 更新了我的答案。
【解决方案2】:

使用extension UIViewController 不使用UIButton

下面的代码扩展了 UIButton

someButton.sayHello() 有效

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

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

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

它适用于“viewDidLoad”

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

例如)

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)
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多