首页 > 解决方案 > 从 UIViewController 向 UIView 发送数据

问题描述

我正在尝试将数据从 UIViewController 发送到 UIView。我到处看了看,但似乎没有一个能正常工作。如下所示,当用户选择特定行时,我试图将 popup.priceLabel.text 和 popup.notificationLabel.text 从 UIViewcontroller 发送到 UIView。我尝试使用 segue、协议和其他方法,但似乎没有任何效果。以下是我想要完成的(我知道它不正确,但只是为了说明意图):

//UIViewController

class CouponsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("selected = \(indexPath.row)")
    let popup = PopUpWindow()
    popup.priceLabel.text = "100.00"
    popup.notificationLabel.text = "Store"
    handleShowPopUp()
}

@objc func handleShowPopUp() {
    popUpWindow.showSuccessMessage = success
    success = !success
    popUpWindow.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
    popUpWindow.alpha = 0
}
}
//UIView

class PopUpWindow: UIView {
    var delegate: PopUpDelegate?

    var showSuccessMessage: Bool? {
        didSet {
            guard showSuccessMessage != nil else { return }
            priceLabel.text = ""
            notificationLabel.text = ""
            priceLabel.textColor = UIColor(red: 147/255, green: 227/255, blue: 105/255, alpha: 1)
        }
    }
}

标签: swiftuitableviewuiviewseguepopupwindow

解决方案


我认为您尝试了 segue insidedidSelectRowAt()方法,但是它不起作用,因为您尝试在不初始化的情况下传递数据,priceLabel notificationLabel因此还有另一种方法可以完成它。您需要在您popupView的价格和通知中创建一个变量。

var price: String = ""

在您的didSelectRowAt()方法中,您需要做的是popup.price = "100.0". 然后在弹出窗口的viewDidLoad()方法中,您需要执行以下操作。

priceLabel.text = price

推荐阅读