我需要从另一个 UIViewController
更改 UIButton
(status, title)
我试过下面的
import UIKit
class ViewController: UIViewController{
@IBOutlet var B1: UIButton!
@IBOutlet var B2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
import Foundation
import UIKit
class View2: UIViewController {
@IBAction func Dismiss(_ sender: Any) {
h()
dismiss(animated: true, completion: nil)
}
func h(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "VC") as? ViewController
vc?.loadViewIfNeeded()
print("c: ",vc?.B1.currentTitle ?? "")
vc?.B1.setTitle("a", for: .normal)
print("c: ",vc?.B1.currentTitle ?? "")
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
输出是:
c: V1B1
c: a
它已更改(如输出所示)!但是当 View 消失时,它会返回到“V1B1”,这是我在 Main.storyboard
我还尝试用协议(protocol)和委托(delegate)来改变它
import UIKit
class ViewController: UIViewController,TestDelegate {
func t(NewT: UIButton) {
NewT.setTitle("a", for: .normal)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dd = segue.destination as? View2 {
dd.d = self
print("B1O: ",B1.currentTitle!)
}
}
@IBOutlet var B1: UIButton!
@IBOutlet var B2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
import Foundation
import UIKit
protocol TestDelegate {
func t(NewT: UIButton)
}
class View2: UIViewController {
var d: TestDelegate?
@IBAction func Dismiss(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "VC") as? ViewController
vc?.loadViewIfNeeded()
print("B1: ",vc?.B1.currentTitle!)
d?.t(NewT: (vc?.B1!)!)
print("B1: ",vc?.B1.currentTitle!)
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
输出:
B1O: V1B1
B1: Optional("V1B1")
B1: Optional("a")
代码有什么问题?
即使 UIViewController
再次加载,我如何永久更改 UIButtons
最佳答案
import UIKit
class ViewController: UIViewController{
@IBOutlet var B1: UIButton!
@IBOutlet var B2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
open override func viewWillAppear(_ animated: Bool) {
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(self.updateTitle), name: NSNotification.Name(rawValue: "buttonTitleUpdate"), object: nil)
super.viewWillAppear(animated)
}
@objc func updateTitle() -> Void {
print("c: ",B1.currentTitle ?? "")
B1.setTitle("a", for: .normal)
print("c: ",B1.currentTitle ?? "")
}
}
import Foundation
import UIKit
class View2: UIViewController {
@IBAction func Dismiss(_ sender: Any) {
// Post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "buttonTitleUpdate"), object: nil)
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
关于swift - 从不同的 ViewController 更改 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55947147/