swift 惰性按钮的目标操作不起作用

x33g5p2x  于 2022-12-17  发布在  Swift
关注(0)|答案(2)|浏览(116)

使用Swift 5.1.3、iOS13.3、XCode11.3、
我尝试创建一个简单的按钮目标操作。
但是,Button位于其自己的StackView类中,而且是一个惰性按钮。
为什么目标操作在我的代码中不起作用?例如,从未调用callButtonMethod
可能是因为API响应太晚了,还是因为一个懒惰的按钮不能执行目标操作。我现在毫无头绪。
谢谢你的帮助。
下面是我的代码:

class CockpitHeaderStackView: UIStackView {

    weak var profileBtnDelegate: CallButtonProfileImage?

    var profileImageView = UIImageView()
    var profileName = "Cockpit".localized

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {

        if let profile = MyAPI.profile, let person = profile.person {
            profileName = "\(person.firstName ?? "") \(person.lastName ?? "")"
        }

        MyAPI.getPicture(PictureType.avatar) { [weak self] (error, image) in

            guard let self = self else { return } // check if self still alive otherwise bail out

            DispatchQueue.main.async {

                if let image = image {
                    self.profileImageView.image = image
                } else {
                    self.profileImageView.image = #imageLiteral(resourceName: "profile-placeholder-small")
                }
                self.profileImageView.contentMode = .scaleAspectFill

                self.axis = .horizontal
                self.alignment = .bottom
                self.spacing = 10.0
                self.addArrangedSubview(self.titleLabel)
                self.addArrangedSubview(self.button)
            }
        }
    }

    lazy var titleLabel: UILabel = {
        let labelWidth: CGFloat = UIScreen.main.bounds.width - 16.0 - 10.0 - 36.0 - 16.0   // FullScreenWidth minus (Leading + Spacing + ButtonWidth + Trailing)
        let label = UILabel()
        label.font = AppConstants.Font.NavBar_TitleFont
        label.text = profileName
        label.textColor = .white
        label.tintColor = .white
        label.widthAnchor.constraint(equalToConstant: labelWidth).isActive = true
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    lazy var button: UIButton = {

        let buttonWidth: CGFloat = 36.0
        let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: buttonWidth, height: buttonWidth)))

        button.setImage(self.profileImageView.image, for: .normal)
        button.addTarget(self, action: #selector(callButtonMethod), for: .touchUpInside)
        button.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
        button.layer.cornerRadius = button.frame.size.width / 2
        button.layer.masksToBounds = false
        button.clipsToBounds = true

        button.translatesAutoresizingMaskIntoConstraints = false
        button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
        button.heightAnchor.constraint(equalToConstant: buttonWidth).isActive = true

        return button
    }()

    @objc func callButtonMethod() {
        profileBtnDelegate?.callProfileBtnMethod()
    }
}

CockpitHeaderStackView用于创建ViewController的自定义导航栏。
下面是使用CockpitHeaderStackView的自定义导航栏的代码:

protocol CallButtonProfileImage: AnyObject {
    func callProfileBtnMethod()
}

class MyViewController: UIViewController {

    // ...

    lazy var titleStackView: CockpitHeaderStackView = {
        let titleStackView = CockpitHeaderStackView(frame: CGRect(origin: .zero, size: CGSize(width: view.bounds.width, height: 88.0)))
        titleStackView.translatesAutoresizingMaskIntoConstraints = false
        return titleStackView
    }()

    lazy var cockpitHeaderView: UIView = {
        let cockpitHeaderView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: view.bounds.width, height: 88.0)))
        cockpitHeaderView.addSubview(titleStackView)
        titleStackView.leadingAnchor.constraint(equalTo: cockpitHeaderView.leadingAnchor, constant: 16.0).isActive = true
        titleStackView.topAnchor.constraint(equalTo: cockpitHeaderView.topAnchor).isActive = true
        titleStackView.trailingAnchor.constraint(equalTo: cockpitHeaderView.trailingAnchor, constant: -16.0).isActive = true
        titleStackView.bottomAnchor.constraint(equalTo: cockpitHeaderView.bottomAnchor).isActive = true
        return cockpitHeaderView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // ...

        view.clipsToBounds = true

        navigationController?.set_iOS12_lookAndFeel()
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        navigationItem.largeTitleDisplayMode = .always
    }

    override func viewWillLayoutSubviews() {
        // replace NavBar title by custom cockpitHeaderView
        self.title = ""
        self.navigationItem.titleView = self.cockpitHeaderView
        // position the cockpitHeaderView inside the largeTitleDisplayMode NavBar
        self.cockpitHeaderView.translatesAutoresizingMaskIntoConstraints = false
        self.cockpitHeaderView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        if let navBarBottomAnchor = self.navigationController?.navigationBar.bottomAnchor {
            if UIScreen.main.bounds.height > 568.0 {
                self.cockpitHeaderView.topAnchor.constraint(equalTo: navBarBottomAnchor, constant: -48.0).isActive = true
            } else {
                self.cockpitHeaderView.topAnchor.constraint(equalTo: navBarBottomAnchor, constant: -46.0).isActive = true  // iPhone SE space limitation
            }
        } else {
            self.cockpitHeaderView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 89.0).isActive = true
        }
    }

    func callProfileBtnMethod() {
        print("right BarButton called here")
    }
}
tcbh2hod

tcbh2hod1#

我终于找到了“解决办法”:惰性初始化似乎是错误行为的原因。
事实上,当我替换所有的惰性初始化,并消除StackView(称为CockpitHeaderStackView),并把所有的东西放在非惰性的let常量中,那么它就工作了!
下面是最后一段相关代码(也就是说,我将所有内容都放在了viewWillAppear方法中):

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let cardsHorizontalController = CardsHorizontalController()
    self.view.addSubview(cardsHorizontalController.view)
    cardsHorizontalController.view.translatesAutoresizingMaskIntoConstraints = false
    cardsHorizontalController.view.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100.0).isActive = true
    cardsHorizontalController.view.heightAnchor.constraint(equalToConstant: 279).isActive = true
    cardsHorizontalController.view.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true

    navigationController?.set_iOS12_lookAndFeel()
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    navigationItem.largeTitleDisplayMode = .always

    PeaxAPI.getPicture(PictureType.avatar) { [weak self] (error, image) in

        guard let self = self else { return } // check if self still alive otherwise bail out

        DispatchQueue.main.async {

            if let image = image {
                self.profileImageView.image = image
            } else {
                self.profileImageView.image = #imageLiteral(resourceName: "profile-placeholder-small")
            }
            self.profileImageView.contentMode = .scaleAspectFill

            if let profile = PeaxAPI.profile, let person = profile.person {
                self.profileName = "\(person.firstName ?? "") \(person.lastName ?? "")"
            }

            let titleStackView = UIStackView(frame: CGRect(origin: .zero, size: CGSize(width: self.view.bounds.width, height: 88.0)))
            titleStackView.isUserInteractionEnabled = true
            titleStackView.translatesAutoresizingMaskIntoConstraints = false

            titleStackView.axis = .horizontal
            titleStackView.alignment = .bottom
            titleStackView.spacing = 10.0

            let labelWidth: CGFloat = UIScreen.main.bounds.width - 16.0 - 10.0 - 36.0 - 16.0   // FullScreenWidth minus (Leading + Spacing + ButtonWidth + Trailing)
            let label = UILabel()
            label.font = AppConstants.Font.NavBar_TitleFont
            label.text = self.profileName
            label.textColor = .white
            label.tintColor = .white
            label.widthAnchor.constraint(equalToConstant: labelWidth).isActive = true
            label.translatesAutoresizingMaskIntoConstraints = false

            let buttonWidth: CGFloat = 36.0
            let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: buttonWidth, height: buttonWidth)))

            button.setImage(self.profileImageView.image, for: .normal)
            button.isUserInteractionEnabled = true
            button.addTarget(self, action: #selector(self.callProfileBtnMethod), for: .touchUpInside)
            button.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
            button.layer.cornerRadius = button.frame.size.width / 2
            button.layer.masksToBounds = false
            button.clipsToBounds = true

            button.translatesAutoresizingMaskIntoConstraints = false
            button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
            button.heightAnchor.constraint(equalToConstant: buttonWidth).isActive = true

            titleStackView.addArrangedSubview(label)
            titleStackView.addArrangedSubview(button)

            let cockpitHeaderView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: self.view.bounds.width, height: 88.0)))
            cockpitHeaderView.isUserInteractionEnabled = true
            cockpitHeaderView.addSubview(titleStackView)
            titleStackView.leadingAnchor.constraint(equalTo: cockpitHeaderView.leadingAnchor, constant: 16.0).isActive = true
            titleStackView.topAnchor.constraint(equalTo: cockpitHeaderView.topAnchor).isActive = true
            titleStackView.trailingAnchor.constraint(equalTo: cockpitHeaderView.trailingAnchor, constant: -16.0).isActive = true
            titleStackView.bottomAnchor.constraint(equalTo: cockpitHeaderView.bottomAnchor).isActive = true

            // replace NavBar title by custom cockpitHeaderView
            self.title = ""
            self.navigationItem.titleView = cockpitHeaderView
            cockpitHeaderView.sizeToFit()
        }
    }
}
6qftjkof

6qftjkof2#

我不得不在添加按钮作为子视图后添加addTarget,这很有效

相关问题