我用的是Xcode和Swift。我有一个班
UIViewController
我在用。关于这个
ui视图控制器
我想用我的自定义类呈现某种弹出视图
ConnectionLostView
. 关于这个
UIView
有一个
UIButton
. 如果你按下按钮
tryToReconnect()
函数被调用(有效)。此函数用于处理联机数据(也适用),并应使用
DispatchQueue.main.async { //updating UI }
但是我的用户界面没有更新(或者更确切地说,我不能从它的超级视图中删除我的按钮,但是我可以删除自己(什么是真正有效的,什么不是你在下面的代码中看到的注释))。
这就是
ui视图控制器
我习惯于陈述我的观点。
class vc: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let connectionStatusView = ConnectionLostView()
connectionStatusView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(connectionStatusView)
//setting up the constraints for connectionStatusView
}
}
这是我的班级
UIVIEW
:
class ConnectionLostView: UIView {
let tryAgainButton = UIButton(type: .roundedRect)
func tryToReconnect() {
let url = URL(string: "http://worldclockapi.com/api/json/est/now")!
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
if let data = json["data"] as? String {
// code for processing the data
DispatchQueue.main.async {
self.removeFromSuperview() //Does work
self.tryAgainButton.removeFromSuperview() // does not work
}
}
}
} catch {
print(error)
}
}
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
//setting up the button
let buttonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)]
let attributedButtonString = NSAttributedString(string: "Try To Reconnect", attributes: buttonAttributes)
let reconnectButton = UIButton(type: .roundedRect)
reconnectButton.translatesAutoresizingMaskIntoConstraints = false
reconnectButton.setAttributedTitle(attributedButtonString, for: .normal)
reconnectButton.addTarget(self, action: #selector(tryToReconnect), for: .touchUpInside)
addSubview(reconnectButton)
// setting up constraints for reconnectButton
}
}
如何修复我的代码,以便在按
reconnectButton
?