我是Xcode和Swift的初学者,目前我正在创建一个应用程序,用户在该应用程序中添加一个人,然后在该应用程序中更正他们欠该人或该人的钱。
实际上,我想在导航栏大标题上向用户显示他们与其他用户的当前平衡,目前我正在使用frame来实现这一点,在frame中,我定义了由UILabel替换的frame的宽度、高度和x、y位置。但是,我希望导航栏大标题上的余额被替换。我想在过去的三天里找到解决办法,你能帮我吗?提前多谢了

import UIKit

class PersonDetailTableViewController: UITableViewController {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext



    var person: People?
    var owe: Owe?

    @IBOutlet var personTable: UITableView!

    var dataInfo: [Owe] = []
    var selectedObject: [Owe] = []
    var balanceAmount = "Balance: "

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (dataInfo.count)
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = personTable
            .dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
        cell.textLabel?.text = dataInfo[indexPath.row].name
        cell.detailTextLabel?.text = "₹ \(dataInfo[indexPath.row].amount)"
        if dataInfo[indexPath.row].amount < 0 {
            cell.detailTextLabel?.textColor = UIColor.red
        } else {
            cell.detailTextLabel?.textColor = UIColor.green
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedObject = [dataInfo[indexPath.row]]
        performSegue(withIdentifier: "addOweDetails", sender: nil)
        tableView.deselectRow(at: indexPath, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getData()
        personTable.dataSource = self
        addTotalToNav()
        print(dataInfo as Any)
    }



    // MARK: - Table view data source

    func addTotalToNav() -> Void {
        if let navigationBar = self.navigationController?.navigationBar {
            let totalFrame = CGRect(x: 20, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)

            let totalLabel = UILabel()
            totalLabel.text = balanceAmount
            totalLabel.tag = 1
            totalLabel.font = UIFont.boldSystemFont(ofSize: 14)
            totalLabel.textColor = UIColor.red
            navigationBar.addSubview(totalLabel)
        }
    }
    func getData() -> Void {
        do{
            dataInfo = try context.fetch(Owe.fetchRequest())
            var total:Double = 0.00
            for i in 0 ..< dataInfo.count {
                total += dataInfo[i].amount as! Double
            }
            balanceAmount = "Balance: ₹" + (NSString(format: "%.2f", total as CVarArg) as String)
        }
        catch{
            print("Fetching Failed")
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! NewOweTableViewController
        vc.dataInfo = selectedObject
        selectedObject.removeAll()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
        personTable.reloadData()
        if (self.navigationController?.navigationBar.viewWithTag(1)?.isHidden == true){
            self.navigationController?.navigationBar.viewWithTag(1)?.removeFromSuperview()
            addTotalToNav()
        }
    }

}

最佳答案

Swift 3.0使用下面的方法创建NavigationBarTitleNavigationBarSubTitle

func setTitle(title:String, subtitle:String) -> UIView {
    let titleLabel = UILabel(frame: CGRect(x:0,y: -8 ,width: 0,height: 0))
    titleLabel.backgroundColor = UIColor.clear
    titleLabel.textColor = UIColor.black
    titleLabel.font = UIFont.systemFont(ofSize: 22)
    titleLabel.text = title
    titleLabel.sizeToFit()

    let subtitleLabel = UILabel(frame: CGRect(x:0,y:18,width: 0,height :0))
    subtitleLabel.backgroundColor = UIColor.clear
    subtitleLabel.textColor = UIColor.black
    subtitleLabel.font = UIFont.systemFont(ofSize: 12)
    subtitleLabel.text = subtitle
    subtitleLabel.sizeToFit()

    let titleView = UIView(frame: CGRect(x:0,y:0,width : max(titleLabel.frame.size.width, subtitleLabel.frame.size.width),height: 30))
    titleView.addSubview(titleLabel)
    titleView.addSubview(subtitleLabel)

    let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width

    if widthDiff < 0 {
        let newX = widthDiff / 2
        subtitleLabel.frame.origin.x = abs(newX)
    } else {
        let newX = widthDiff / 2
        titleLabel.frame.origin.x = newX
    }
    return titleView
}

viewDidLoad()中使用
override func viewDidLoad() {
    super.viewDidLoad()
self.navigationItem.titleView = setTitle(title: "My Events", subtitle: "Sub Title")
}

10-05 20:05