任何人都可以帮我理解我的代码中的错误。我没有得到它我的代码编译没有任何错误,但我的图像没有显示。我相信我的图像存在于资产文件夹中,我也给出了正确的图像名称。我是以编程方式进行的。以下是我的代码 - :
*的AppDelegate - :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
windowLayout()
application.statusBarStyle = .lightContent
return true
}
func windowLayout()
{
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 238/255, green: 32/255, blue: 31/255, alpha: 1)
let statusBarView = UIView()
statusBarView.backgroundColor = UIColor(colorLiteralRed: 194/255, green: 31/255, blue: 31/255, alpha: 1)
window?.addSubview(statusBarView)
window?.translatesAutoresizingMaskIntoConstraints = false
//window?.addConstraintsWithFormat(format: "H:|[v0]|", views: statusBarView)
//window?.addConstraintsWithFormat(format: "V:|[v0(20)]", views: statusBarView)
UINavigationBar.appearance().shadowImage = UIImage()
//UINavigationBar.appearance().setBackgroundImage(UIImage(),forBarMatrics: .default)
}
扩展程序文件 - :
import UIKit
protocol navigationBarItems {
func searchBarButton()
func handleMoreButton()
}
extension UINavigationController:navigationBarItems
{
func handleMoreButton() {
}
func searchBarButton()
{
let searchBarImage = UIImage(named: "search-icon")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let searchImage = UIBarButtonItem(image: searchBarImage, style: UIBarButtonItemStyle.done, target: self, action: #selector(handleSearch))
navigationItem.rightBarButtonItem = searchImage
}
func handleSearch()
{
print("123")
}
}
控制器类 - :
class HomeController: UICollectionViewController,UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
setUpLayout()
setUpMenuBar()
fetchJsonData()
navigationController?.searchBarButton()
}
我已经通过设置断点来检查我的功能是否被调用。它工作正常,但图像没有显示请帮助。
答案 0 :(得分:2)
尝试扩展UIViewController而不是UINavigationController
extension UIViewController:navigationBarItems
{
func handleMoreButton() {
}
func searchBarButton()
{
let searchBarImage = UIImage(named: "search-icon")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let searchImage = UIBarButtonItem(image: searchBarImage, style: UIBarButtonItemStyle.done, target: self, action: #selector(handleSearch))
navigationItem.rightBarButtonItem = searchImage
}
func handleSearch()
{
print("123")
}
}
现在从`viewDidLoad``
调用此方法class HomeController: UICollectionViewController,UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
setUpLayout()
setUpMenuBar()
fetchJsonData()
self.searchBarButton()
}