我在导航栏中有三个 View 。
我想在导航栏上放置标签,这样当我从一个 View 转到另一个 View 时,它会显示页码。这是我的代码。我在所有三个类的viewDidLoad中都写了这段代码
if let navigationBar = self.navigationController?.navigationBar {
let firstFrame = CGRect(x: navigationBar.frame.width/2, y: 8, width: 15, height: 10)
let secondFrame = CGRect(x: navigationBar.frame.width/2 + 30, y: 8, width: 15, height: 10)
let thirdFrame = CGRect(x: navigationBar.frame.width/2 + 60, y: 8, width: 15, height: 10)
let firstLabel = UILabel(frame: firstFrame)
firstLabel.text = "1"
let secondLabel = UILabel(frame: secondFrame)
secondLabel.text = "of"
let thirdLabel = UILabel(frame: thirdFrame)
secondLabel.text = "3"
navigationBar.addSubview(firstLabel)
navigationBar.addSubview(secondLabel)
navigationBar.addSubview(thirdLabel)
}
但问题是相同的标签在每个 View Controller 中重复。它在每个 View Controller 中显示为“1 of 3” *
最佳答案
首先创建UINavigationController的子类
class NavigationController: UINavigationController {
}
不要忘记在 Storyboard 中更改 UINavigationController
的类
现在在您的 UINavigationController
子类中创建标签的属性并设置它们
class NavigationController: UINavigationController {
var firstLabel: UILabel?
var secondLabel: UILabel?
var thirdLabel: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
firstLabel = UILabel(frame: CGRect(x: navigationBar.frame.width/2, y: 8, width: 15, height: 10))
secondLabel = UILabel(frame: CGRect(x: navigationBar.frame.width/2 + 30, y: 8, width: 15, height: 10))
thirdLabel = UILabel(frame: CGRect(x: navigationBar.frame.width/2 + 60, y: 8, width: 15, height: 10))
navigationBar.addSubview(firstLabel)
navigationBar.addSubview(secondLabel)
navigationBar.addSubview(thirdLabel)
firstLabel.text = "1"
secondLabel.text = "of"
thirdLabel.text = "3"
}
}
然后你想在每次移动到另一个 ViewController 时更改 firstLabel.text
。因此,在 viewWillAppear
的 ViewController 中为您的 NavigationController
获取引用并像这样设置此 firstLabel
的文本
class ViewController1: UIViewController {
override func viewWillAppear(_ animated: Bool) {
if let navController = navigationController as? NavigationController {
navController.firstLabel?.text = "1"
}
}
}
然后对第二个和第三个 UIViewController
class ViewController2: UIViewController {
override func viewWillAppear(_ animated: Bool) {
if let navController = navigationController as? NavigationController {
navController.firstLabel?.text = "2"
}
}
}
...
关于ios - swift 导航栏上的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53452136/