第一个问题。 我可以在段之间切换,但应用程序不识别切换,永远不会运行选择器功能。
第二个问题:我的导航栏标题不显示。 导航栏的标题不显示。
下面是代码。
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 = {
这应该能让你的分段控制选择器正常启动。
至于显示你的导航项的 title
嗯... ... 你不能真正做到这一点。和 在导航栏中显示一个自定义的视图 titleView
. 要么选择一个,要么选择另一个