Ios 为什么导航栏中分段控件的选择器不起作用?
第一期:Ios 为什么导航栏中分段控件的选择器不起作用?,ios,swift,uinavigationbar,uisegmentedcontrol,Ios,Swift,Uinavigationbar,Uisegmentedcontrol,第一期: 我可以在段之间切换,但应用程序无法识别切换,并且从不运行选择器功能 第二期: 导航栏标题不显示 代码如下: class ViewController: UIViewController { let mySegmentControl: UISegmentedControl = { let sc = UISegmentedControl(items: ["First","Second","Third"]) sc.translatesAutores
我可以在段之间切换,但应用程序无法识别切换,并且从不运行选择器功能 第二期:
导航栏标题不显示 代码如下:
class ViewController: UIViewController {
let mySegmentControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["First","Second","Third"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
sc.selectedSegmentIndex = 0
if #available(iOS 13.0, *) {
sc.selectedSegmentTintColor = .red
} else {
// Fallback on earlier versions
sc.tintColor = .red
}
return sc
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationController?.navigationBar.tintColor = .blue
navigationController?.navigationBar.barTintColor = .yellow
navigationItem.title = "My App"
self.navigationItem.titleView = mySegmentControl
}
@objc func handleSegmentChange() {
let chosedIndex = mySegmentControl.selectedSegmentIndex
print(chosedIndex)
}
}
在您创建的
mySegmentConstrol
的闭包中,self
并不指您认为它所做的事情。在这种情况下,self
指的是类型为(ViewController)->()->ViewController
,这肯定不是您想要的:
要引用当前的ViewController
实例,请将mySegmentControl
声明为lazy var
:
lazy var mySegmentControl: UISegmentedControl = {
这将使分段控制选择器正确启动
至于显示导航项的
标题
,那么。。。您不能在导航栏的标题视图中显示自定义视图。它是一个或另一个。在您创建的mySegmentConstrol
的闭包中,self
并不指您认为它所做的事情。在这种情况下,self
指的是类型为(ViewController)->()->ViewController
,这肯定不是您想要的:
要引用当前的ViewController
实例,请将mySegmentControl
声明为lazy var
:
lazy var mySegmentControl: UISegmentedControl = {
这将使分段控制选择器正确启动
至于显示导航项的标题
,那么。。。您不能在导航栏的标题视图中显示自定义视图。这是一个或另一个