简体   繁体   中英

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

I have made extension file like this :

import Foundation
import Swift
import UIKit

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

在此处输入图片说明

and Then call sayHello method in view controller like this:

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

But show this error:
在此处输入图片说明

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

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

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

If you want to create a UIButton extension

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

then you will need to call it on UIButton like below

let button = UIButton()
button.sayHello()

use extension UIViewController not use UIButton

below code extend UIButton so

someButton.sayHello() is works

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

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

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

it works in '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)
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM