简体   繁体   中英

How to make the UILabel replace the NavigationBar large title?

I am a beginner to Xcode and Swift and I am currently creating an application where the user adds a person on the application and after that it right the amount of money they owe that person or that person owes him/her.

I actually want to show the user their current balance with other user on NavigationBar Large title and currently I am doing that by using frame where I define the width, height and x,y positions of frame that is replaced by UILabel. However, I wish the balance to be replaced on the NavigationBar Large Title. I am trying to find a solution to this from past 3 days therefore can you please help me? Thanks a lot in advance

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 Use below method to create NavigationBarTitle and NavigationBarSubTitle

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
}

Use this in viewDidLoad()

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

Here is the code, just set the titleView to your label:

let customLabel = UILabel()
// config your label here
navigationItem?.titleView = customLabel

您可以使用navigationBar.topItem?.titleView = totalLabel代替navigationBar.addSubview(totalLabel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM