在Swift 5中实现两个垂直按钮的删除可以通过以下步骤完成:
let button1 = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
button1.setTitle("Button 1", for: .normal)
button1.backgroundColor = UIColor.blue
let button2 = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 50))
button2.setTitle("Button 2", for: .normal)
button2.backgroundColor = UIColor.red
button1.addTarget(self, action: #selector(deleteButton(_:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(deleteButton(_:)), for: .touchUpInside)
@objc func deleteButton(_ sender: UIButton) {
sender.removeFromSuperview()
}
self.view.addSubview(button1)
self.view.addSubview(button2)
完整的示例代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
button1.setTitle("Button 1", for: .normal)
button1.backgroundColor = UIColor.blue
button1.addTarget(self, action: #selector(deleteButton(_:)), for: .touchUpInside)
let button2 = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 50))
button2.setTitle("Button 2", for: .normal)
button2.backgroundColor = UIColor.red
button2.addTarget(self, action: #selector(deleteButton(_:)), for: .touchUpInside)
self.view.addSubview(button1)
self.view.addSubview(button2)
}
@objc func deleteButton(_ sender: UIButton) {
sender.removeFromSuperview()
}
}
这样,当点击按钮时,对应的按钮将会被从视图中删除。
领取专属 10元无门槛券
手把手带您无忧上云