调用将在另一个类中隐藏按钮的函数-Swift

时间:2018-10-29 22:21:31

标签: ios swift class button

我正在尝试创建一个IMDB风格的电影应用程序,当用户不登录并按“跳过”按钮时,“收藏夹”(将电影添加到收藏夹)按钮将消失。

LandingViewController是“跳过”按钮的位置,MovieTableViewCell是所有数据的显示位置。

我应该怎么做才能使hide操作在函数内部起作用?这背后的逻辑是什么?我想念什么?

请检查代码中的以下注释。谢谢!

import UIKit

class LandingViewController: UIViewController {
    @IBOutlet weak var skipButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBAction func didTapSkip(_ sender: Any) {
    MovieTableViewCell().hideButton()
   }

import UIKit

class MovieTableViewCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var ratingLabel: UILabel!
    @IBOutlet weak var languageLabel: UILabel!
    @IBOutlet weak var releaseYearLabel: UILabel!
    @IBOutlet weak var posterImage: UIImageView!
    @IBOutlet weak var favoriteButton: UIButton?




    override func awakeFromNib() {
        super.awakeFromNib()
        favoriteButton?.isHidden = true  // works here for some reason
    }


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)


    }

    func hideButton() {
        favoriteButton?.isHidden = true  // doesn't work and If I unwrap it, the app will crash, because it will find the buttton as NIL for some reason
        print("hidebutton") // the print works so the function works when the skip is pressed

    }

1 个答案:

答案 0 :(得分:0)

尝试使用NSUserDefaults

在LandingViewController中

@IBAction func didTapSkip(_ sender: Any) {
    UserDefaults.standard.set(true, forKey: "didSkip")
}

在MovieTableViewCell中

override func awakeFromNib() {
    super.awakeFromNib()
    if UserDefaults.standard.bool(forKey: "didSkip") {
        favoriteButton?.isHidden = true  
    } else {
        favoriteButton?.isHidden = false  
    }
}