ios - UILabel 文本即使具有新值也不会更新,已尝试一切

标签 ios swift3 uilabel

我正在使用 UICollectionView didSelectItemAt 来更新我在 HomeController 中设置的 UI 标签。所以基本上当我按下单元格时,我希望我的文本被更新。但是文本没有更新,虽然我已经调试并且值发生了变化。我已经尝试了所有方法,包括 setNeedsDisplay() 和通过 main thread 运行(它已经这样做了)

我在这些类中有很多代码(我不使用 storyboard)但这是标签设置(位于 HomeController 中):

import UIKit
import CoreData

class mainHomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
static let sharedInstance = HomeController()

    override func viewDidLoad() {
        super.viewDidLoad()


        setupBasketBar()

    }

    let totNumber: UILabel = {
        let label = UILabel()
        label.text = "0"
        label.numberOfLines = 2
        return label
    }()

    func setupBasketBar() {

        self.view.addSubview(totNumber)
        totNumber.translatesAutoresizingMaskIntoConstraints = false
        totNumber.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 330).isActive = true
        totNumber.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        totNumber.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
        totNumber.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 5).isActive = true


    }

}

这位于提要单元格中:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    HomeController.sharedInstance.totNumber.text = ("234")
    HomeController.sharedInstance.totNumber.setNeedsDisplay()


}

我已经删除了相关部分。

这是 HomeController 的完整代码:

import UIKit
import CoreData

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    static let sharedInstance = HomeController()

    let cellId = "cellId"
    let trendingCellId = "trendingCellId"
    let subscriptionCellId = "subscriptionCellId"

    let titles = ["Home", "Trending", "Subscriptions", "Account"]

    override func viewDidLoad() {

        super.viewDidLoad()

        navigationController?.navigationBar.isTranslucent = false

        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: view.frame.height))
        titleLabel.text = "Home"
        titleLabel.textColor = UIColor.black
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        navigationItem.titleView = titleLabel

        setupCollectionView()
        setupMenuBar()
        setupBasketBar()

    }

    func setupCollectionView() {
        if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.scrollDirection = .horizontal
            flowLayout.minimumLineSpacing = 0
        }

        collectionView?.backgroundColor = UIColor.white
        collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
        collectionView?.register(TrendingCell.self, forCellWithReuseIdentifier: trendingCellId)
        collectionView?.register(SubscriptionCell.self, forCellWithReuseIdentifier: subscriptionCellId)


        collectionView?.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
        collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0)

        collectionView?.isPagingEnabled = true
    }

    lazy var settingsLauncher: SettingsLauncher = {
        let launcher = SettingsLauncher()
        launcher.homeController = self
        return launcher
    }()

    func handleMore() {
        //show menu
        settingsLauncher.showSettings()
    }

    func showControllerForSetting(_ setting: Setting) {
        let dummySettingsViewController = UIViewController()
        dummySettingsViewController.view.backgroundColor = UIColor.white
        dummySettingsViewController.navigationItem.title = setting.name.rawValue
        navigationController?.navigationBar.tintColor = UIColor.white
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        navigationController?.pushViewController(dummySettingsViewController, animated: true)
    }

    func handleSearch() {
        scrollToMenuIndex(2)

    }

    func scrollToMenuIndex(_ menuIndex: Int) {
        let indexPath = IndexPath(item: menuIndex, section: 0)
        collectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)

        setTitleForIndex(menuIndex)
    }


    fileprivate func setTitleForIndex(_ index: Int) {
        if let titleLabel = navigationItem.titleView as? UILabel {
            titleLabel.text = "  \(titles[index])"
        }

    }

    lazy var menuBar: MenuBar = {
        let mb = MenuBar()
        mb.homeController = self
        return mb
    }()

    func buttonAction(sender: UIButton!) {
        let btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {

            let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

            let vc: UINavigationController = storyboard.instantiateViewController(withIdentifier: "NewViewController") as! UINavigationController

            self.present(vc, animated: true, completion: nil)

        }

    }

    let totLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
    let btn: UIButton = UIButton(frame: CGRect(x: 0, y: 600, width: 500, height: 80))

    func setupBasketBar() {

        //Checkout button
        btn.backgroundColor = UIColor.rgb(36, green: 51, blue: 70)

        btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        btn.tag = 1
        self.view.addSubview(btn)
        btn.setTitleColor(UIColor.yellow, for: .normal)

        //Button that updates the current amount

        totLabel.text = "Total amount"
        totLabel.textColor = UIColor.white
        self.view.addSubview(totLabel)

        //constraints

        totLabel.translatesAutoresizingMaskIntoConstraints = false
        totLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
        totLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        totLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
        totLabel.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.1).isActive = true


        //oldconstraints

      /*  self.view.addSubview(totNumber)
        totNumber.translatesAutoresizingMaskIntoConstraints = false
        totNumber.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 330).isActive = true
        totNumber.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        totNumber.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
        totNumber.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.1).isActive = true*/


    }

    fileprivate func setupMenuBar() {
        navigationController?.hidesBarsOnSwipe = false

        let redView = UIView()
        redView.backgroundColor = UIColor.rgb(36, green: 51, blue: 70)
        view.addSubview(redView)
        view.addConstraintsWithFormat("H:|[v0]|", views: redView)
        view.addConstraintsWithFormat("V:[v0(50)]", views: redView)

        view.addSubview(menuBar)
        view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
        view.addConstraintsWithFormat("V:[v0(50)]", views: menuBar)


        menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
    }


    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {   

        let index = targetContentOffset.pointee.x / view.frame.width

        let indexPath = IndexPath(item: Int(index), section: 0)
        menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)

        setTitleForIndex(Int(index))
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5

    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let identifier: String
        if indexPath.item == 1 {
            identifier = trendingCellId
        } else if indexPath.item == 2 {
            identifier = subscriptionCellId
        } else {
            identifier = cellId
        }

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height - 50)
    }

}

最佳答案

好的!查看更新后的代码片段,绝对不需要 sharedInstance 单例 - 我会完全删除它。

然后 didSelectItemAt 方法只需要是这样的:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    totNumber.text = "234"
}

关于ios - UILabel 文本即使具有新值也不会更新,已尝试一切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230420/

相关文章:

ios - 如何让其他应用程序保存文件到我们的应用程序?

swift - 当枚举符合协议(protocol) CustomStringConvertible 时,是否可以从变量中获取枚举描述?

ios - 当搜索位置时,它在 map 上显示 2 个图钉,而不是 1 个图钉。如何在搜索中仅显示 1 个图钉?

ios - UIButton图像居中文本右侧

ios - UILabel 中的多行字符串格式化问题

ios - 是否可以控制 UITableView 的速度和滚动

ios - iOS项目中的图片存放位置

ios - 如何检测隐私权限更改(例如相机访问)

iphone - 垂直对齐 UILabel 内的文本并使其下方的 View 相应向上移动

ios - Facebook iOS SDK 的 openActiveSession 后访问 token 过期