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