我有一个NowPlayingVC,作为MainVC(一个集合视图)的子级,当第三个viewcontroller(SingleSoundVC)被解雇时,我想在NowPlayingVC中更改一个文本值。
我做任何事情都是通过代码,我不明白为什么解雇后我的标签仍然不可见。
如果我努力编码,它们工作得很好,但从不改变。
当第三个视图被删除但标签为空时,我可以正确地打印,即使我可以用调试视图层次结构看到它。
我尝试过这样的协议/委托:
协议
protocol SendDataToAudioPlayerContainer {
func receiveData(data:Sound){
self.audioNameLabel.text = data.name
}
}
现在播放VC
NowPlayingVC: SendDataToAudioPlayerContainer
var audioNameLabel:UILabel = {
var lbl = UILabel()
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.sizeToFit()
lbl.textColor = .black
return lbl
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupConstraints()
}
func setupViews() {
self.view.backgroundColor = .blue
self.view.addSubview(audioNameLabel)
}
func setupConstraints(){ //setup of constraints with SnapKit}
}
单声道VC
var delegate:SendDataToAudioPlayerContainer?
var singleSound: Sound?
@objc func dismissView(){
if self.delegate != nil {
print("data passed up")
let data = self.singleSound
delegate?.receiveData(data: data!)
self.dismiss(animated: true, completion: nil)
} else {self.dismiss(animated: true, completion: nil)
print("data is not passed")}
}
我还要补充一点,当我选择我现在添加的项目播放作为MainVC的代表时
MainVC-集合视图
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = MainVC()
let childVC = NowPlayingVC()
vc.delegate = childVC
ApiService.sharedInstance.downloadAudioFile(with: vc.singleSound!.audioId)
vc.modalPresentationStyle = .popover
present(vc, animated: true, completion: nil)
}
最佳答案
MainVC-集合视图
您应该为NowPlayingVC创建一个引用同一实例的属性:
var nowPlayingVC=nowPlayingVC()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = SingleSoundVC()
vc.delegate = nowPlayingVC
ApiService.sharedInstance.downloadAudioFile(with: vc.singleSound!.audioId)
vc.modalPresentationStyle = .popover
present(vc, animated: true, completion: nil)
}
协议
应定义为:
protocol SendDataToAudioPlayerContainer {
func receiveData(data:Sound)
}
现在播放VC
采用它来
SendDataToAudioPlayerContainer
协议:添加
func receiveData(data:Sound){
self.audioNameLabel.text = data.name
**// update constraints here**
}
}
关于ios - 取消 View 时更改值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57540191/