项目里需要将searchbar放置在navigationbar上面,于是自定义titleView,并将searchbar作为子视图添加上去,之前一直好好的,不知道为什么后来一push到包含searchbar的控制器,应用就奔溃并抛出:libc++abi.dylib: terminating with uncaught exception of type NSException
override func viewDidLoad() {
super.viewDidLoad()
initializeSearchBar()
// Do any additional setup after loading the view.
}
func initializeSearchBar() {
self.navigationItem.setHidesBackButton(true, animated: true)
titleView = UIView(frame: CGRect(x: 15, y: 7.5, width: Screen.Width, height: 29))
searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: titleView.frame.width - 15, height: titleView.frame.height))
searchBar.placeholder = "搜索"
searchBar.delegate = self
searchBar.showsCancelButton = true
searchBar.tintColor = UIColor.fwNavigationBarColor
searchBar.backgroundImage = UIImage.imageWithColor(UIColor.clear)
let searchTextField = searchBar.value(forKey: "_searchField") as? UITextField
searchTextField?.textColor = UIColor.fwSecondaryLightGray
searchTextField?.font = kFont(14)
searchTextField?.backgroundColor = UIColor.fwTableViewBackgroundColor
let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton
cancelButton?.setTitle("取消", for: .normal)
cancelButton?.titleLabel?.font = kFont(16)
cancelButton?.setTitleColor(UIColor.fwWhite, for: .normal)
titleView.addSubview(searchBar)
self.navigationItem.titleView = titleView
}
解决方案:弃用titleView,而是设置leftBarButtonItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleView)