所以我在使用 SmileLock 库。输入正确密码后再次加载 View 时,我在更改一些文本和 socket 时遇到问题。这是您导航到密码条目 VC 的第一个登录页面。我已尝试通过我的代码中的注释阐明我的问题。
import UIKit
class LoginVC: UIViewController {
//Made this to access this VC from other VCs.
static var instance = LoginVC()
//A button which is activated if the password is correct and goes to the next page.
@IBOutlet weak var enterMainPage: UIButton!
//A label which I'd want to change its text.
@IBOutlet weak var statusSection: UILabel!
//MARK: Property
let isBlurUI = true
var loginVCID: String!
var mainTBCID: String!
override func viewDidLoad() {
super.viewDidLoad()
print("correct 8")
//The button is inactive in every load.
enterMainPage.isEnabled = false
PASSWORD_IS_CORRECT: Bool = false
//This loads up the password entry page when the login button is pressed.
loginVCID = isBlurUI ? "BlrPasswordLoginVC" : "PasswordLoginVC"
}
@IBAction func enterMainPagePressed(_ sender: UIButton) {
}
@IBAction func presentLoginVC(_ sender: AnyObject) {
PASSWORD_IS_CORRECT = true
print("correct 10")
present(loginVCID)
//This was the only way I was not getting any errors (Unexpectedly found nil).
self.loadView()
}
func present(_ id: String) {
let mainVC = storyboard?.instantiateViewController(withIdentifier: id)
mainVC?.modalPresentationStyle = .overCurrentContext
present(mainVC!, animated: true, completion: nil)
}
}
这是密码输入页面,我试图在其中直接更改标签的文本,但最终出现“展开时意外发现 nil”错误。我将在下面的代码中指出:
override func viewDidLoad() {
super.viewDidLoad()
//create PasswordUIValidation subclass
passwordUIValidation = MyPasswordUIValidation(in: passwordStackView)
passwordUIValidation.success = { [weak self] _ in
print("*️⃣ success!")
PASSWORD_IS_CORRECT = true
if PASSWORD_IS_CORRECT {
//This is where I got the unexpected unwrapping error.
LoginVC.instance.statusSection.text = "sample text"
print("password is correct")
}
我所需要的只是能够更改标签的文本和一些其他更改。只要您觉得有必要,请随时更改。
最佳答案
您可以使用Notification
或delegate
Notification
extension Notification.Name {
static let passwordNotification = Notification.Name(
rawValue: "password_Notification")
}
class LoginVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(LoginVC.getPassword),
name: .passwordNotification,
object: nil)
}
@objc func getPassword(_ notification:NSNotification){
if let password = notification.object as? String {
self.statusSection.text = password
}
}
}
在你的密码 Controller 中
删除此 LoginVC.instance.statusSection.text = "sample text"
并添加这个
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .passwordNotification, object: "sample text")
关于ios - 如何从 Swift 中的另一个 View Controller 更改标签的导出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230226/