首页 > 解决方案 > 如何在不同情况下快速启用按钮?

问题描述

我想在不同情况下禁用和启用按钮:

如果用户来到我的共享 viewController 按钮将被禁用:

func handleShareAndAbortButton() {
    shareButton.isEnabled = false
    abortButton.isEnabled = false

    let attributedShareButtonText = NSAttributedString(string: shareButton.currentTitle!, attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0.2) ])
    let attributedabortButtonText = NSAttributedString(string: abortButton.currentTitle!, attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0.2) ])
    shareButton.setAttributedTitle(attributedShareButtonText, for: .normal)
    abortButton.setAttributedTitle(attributedabortButtonText, for: .normal)
}

handleShareAndAbortButton被召唤viewDidLoad

如果发生了变化(图片或文字),我想启用该按钮:

func imageDidChange() {
    selectedText = postTextView.text!

    let isText = selectedText
    let isImage = selectedImage != nil

    if isImage || isText != "Schreibe etwas..." && isText != nil {
    shareButton.isEnabled = true
    abortButton.isEnabled = true

    let attributedShareButtonText = NSAttributedString(string: shareButton.currentTitle!, attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 255, green: 255, blue: 255, alpha: 1.0) ])
    let attributedabortButtonText = NSAttributedString(string: abortButton.currentTitle!, attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1.0) ])
    shareButton.setAttributedTitle(attributedShareButtonText, for: .normal)
    abortButton.setAttributedTitle(attributedabortButtonText, for: .normal)
    }
}

imageDidChange我打电话viewWillAppear

在这里我开始编辑后删除占位符:

   extension ShareViewController: UITextViewDelegate {

    func textViewDidBeginEditing(_ textView: UITextView) {
        if postTextView.textColor == UIColor.lightGray {
            postTextView.text = nil
            postTextView.textColor = UIColor.black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if postTextView.text.isEmpty {
            postTextView.text = "Schreibe etwas..."
            postTextView.textColor = UIColor.lightGray
        }
    }
}

当用户现在输入一些文本时,占位符“Schreibe etwas...”将消失,文本也将是!= nil。但它不起作用。

更新

我发现了问题。当我删除isText != "Schreibe etwas..." 它时,它可以工作。但我需要这个。如何与字符串进行比较?如果我没有此代码,则用户可以始终使用占位符文本进行上传。

在此先感谢您的帮助!

标签: swiftuibutton

解决方案


imageDidChange更改文本后,您永远不会打电话。

采用:

func textViewDidEndEditing(_ textView: UITextView) {
     if postTextView.text.isEmpty {
         postTextView.text = "Schreibe etwas..."
         postTextView.textColor = UIColor.lightGray
     }

     imageDidChange()
}

推荐阅读