簡體   English   中英

單擊時如何刪除按鈕?

[英]How to remove a button when it is clicked?

我是新來的迅速 我已經使用subview創建了multiple textfield and button 我的ViewController的輸出如下: 這里

現在,我需要刪除"-"按鈕,並且單擊它時它是對應的textfield 但是我無法檢測到正在單擊哪個按鈕。 這是我的代碼:

var y: CGFloat = 190
var by: CGFloat = 192

 @IBAction func addRow(sender: AnyObject) {

    y += 30
    by += 30

    let textFiled = UITextField(frame:CGRectMake(50.0, y, 100.0, 20.0))

    textFiled.borderStyle = UITextBorderStyle.Line

    let dunamicButton = UIButton(frame:CGRectMake(155.0, by, 15.0, 15.0))
    dunamicButton.backgroundColor = UIColor.clearColor()
    dunamicButton.layer.cornerRadius = 5
    dunamicButton.layer.borderWidth = 1
    dunamicButton.layer.borderColor = UIColor.blackColor().CGColor
    dunamicButton.backgroundColor = .grayColor()
    dunamicButton.setTitle("-", forState: .Normal)
    dunamicButton.addTarget(self, action: #selector(removeRow), forControlEvents: .TouchUpInside)




    self.view.addSubview(textFiled)
    self.view.addSubview(dunamicButton)
}


func removeRow(sender: UIButton!) {
    print("Button tapped")
    self.view.removeFromSuperview()
}

任何幫助,將不勝感激...

eMKA是對的! 嘗試這個:

import UIKit

class ViewController: UIViewController {

    var y:CGFloat = 100
    var textFields = [UIButton : UITextField]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func onAddMoreButtonPressed(sender: AnyObject) {
        let newButton = UIButton(frame: CGRect(x: 50, y: y, width: 150, height: 20))


        newButton.setTitle("New button", forState: .Normal)
        newButton.backgroundColor = UIColor.blueColor()
        newButton.addTarget(self, action: #selector(ViewController.onNewButtonPressed(_:)), forControlEvents: .TouchUpInside)

        self.view.addSubview(newButton)

        let newTextField = UITextField(frame: CGRect(x: 200, y: y, width: 150, height: 20))
        newTextField.text = "New text field"
        self.view.addSubview(newTextField)

        textFields[newButton] = newTextField

        y += 20
        if y > self.view.frame.height {
            y = 100
        }
    }

    func onNewButtonPressed(sender: UIButton) {
        textFields[sender]?.removeFromSuperview()
        sender.removeFromSuperview()
    }

}

您可以在任何視圖控制器中重寫touchesBegan方法。 假設您將按鈕數組存儲在某處

let buttons : [UIButton] = []

您可以執行以下操作:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    super.touchesBegan(touches, withEvent: event)

    guard let touch: UITouch = touches.first else {
        return
    }

    for button in buttons {
        if touch.view == button {
            print("This is the button you tapped")
            button.removeFromSuperview()
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM