如何在swift按钮上添加一个独立的UIView?

时间:2018-02-13 05:22:24

标签: ios swift xcode uiview

我正在尝试在按下按钮时添加UILabels和其他UIView元素并让它们充当独立元素,但我没有运气。我可以成功添加多个标签和文本字段但是当我尝试使用我的手势识别器删除它们时,它只会删除最新的UIView元素。我的完整代码发布在下面。我的实现中存在两个主要错误:一次创建多个标签或文本字段会导致手势无响应,我只能删除最新的UIView元素。非常感谢任何帮助!

我的模特:

import Foundation
import UIKit

class QuizItem: UIViewController{

var alert = UIAlertController()
var labelCountStepper = 0
var tfCountStepper = 0
let gestureRecog = myLongPress(target: self, action: #selector(gestureRecognized(sender:)))
let moveGesture = myPanGesture(target: self, action: #selector(userDragged(gesture:)))

func createLabel(){
    var randLabel = UILabel(frame: CGRect(x: 200, y: 200, width: 300, height: 20))
    randLabel.isUserInteractionEnabled = true
    randLabel.textColor = UIColor .black
    randLabel.text = "I am a Test Label"
    randLabel.tag = labelCountStepper
    gestureRecog.quizItem = randLabel
    moveGesture.quizItem = randLabel
    randLabel.addGestureRecognizer(self.longPressGesture())
    randLabel.addGestureRecognizer(self.movePanGesture())
    topViewController()?.view.addSubview(randLabel)
    labelCountStepper = labelCountStepper+1
}

func createTextField(){
    var randTextField = UITextField(frame: CGRect(x: 200, y: 200, width: 300, height: 35))
    randTextField.isUserInteractionEnabled = true
    randTextField.backgroundColor = UIColor .lightGray
    randTextField.placeholder = "Enter your message..."
    randTextField.tag = tfCountStepper
    gestureRecog.quizItem = randTextField
    moveGesture.quizItem = randTextField
    randTextField.addGestureRecognizer(self.longPressGesture())
    randTextField.addGestureRecognizer(self.movePanGesture())
    topViewController()?.view.addSubview(randTextField)
    tfCountStepper = tfCountStepper+1
}



func longPressGesture() -> UILongPressGestureRecognizer {
    let lpg = UILongPressGestureRecognizer(target: self, action: #selector(gestureRecognized(sender:)))
    lpg.minimumPressDuration = 0.5
    return lpg
}

func movePanGesture() -> UIPanGestureRecognizer {
    let mpg = UIPanGestureRecognizer(target: self, action: #selector(userDragged(gesture:)))
    return mpg
}

@objc func gestureRecognized(sender: UILongPressGestureRecognizer){
    if(sender.state == .began){
        print("Label Tag #: \(labelCountStepper)")
        print("Text Field Tag #: \(tfCountStepper)")
        alert = UIAlertController(title: "Remove Item?", message: nil, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
            self.gestureRecog.quizItem.removeFromSuperview()
        }))

        alert.addAction(UIAlertAction(title: "No", style: .cancel){(_) in

        })

        topViewController()?.present(alert, animated: true, completion: nil)
    }
}

@objc func userDragged(gesture: UIPanGestureRecognizer){
    let loc = gesture.location(in: self.view)
    moveGesture.quizItem.center = loc

}

override func viewDidLoad() {
    super.viewDidLoad()
}

func topViewController() -> UIViewController? {
    guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
    while topViewController.presentedViewController != nil {
        topViewController = topViewController.presentedViewController!
    }
    return topViewController
}

}

我的ViewController:

import UIKit

class ViewController: UIViewController {

var labelMaker = QuizItem()


@IBAction func createLabel(_ sender: UIButton) {
    labelMaker.createLabel()
}

@IBAction func createTextField(_ sender: UIButton) {
    labelMaker.createTextField()
}
override func viewDidLoad() {

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

我还创建了两个继承自UILongPress和UIPan Gesture Recognizers的子类。我只发布了LongPress,因为UIPan完全相同 - 只是从UIPan而不是UILongPress继承。

import Foundation
import UIKit
class myLongPress: UILongPressGestureRecognizer{

var quizItem = UIView()

}

1 个答案:

答案 0 :(得分:1)

您可以通过轻微更改代码来实现这一目标:

@objc func gestureRecognized(sender: UILongPressGestureRecognizer){
    if(sender.state == .began){
        print("Label Tag #: \(labelCountStepper)")
        print("Text Field Tag #: \(tfCountStepper)")
        alert = UIAlertController(title: "Remove Item?", message: nil, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
            let selectedView = sender.view
            selectedView?.removeFromSuperview()
        }))

        alert.addAction(UIAlertAction(title: "No", style: .cancel){(_) in

        })

        topViewController()?.present(alert, animated: true, completion: nil)
    }
}

@objc func userDragged(gesture: UIPanGestureRecognizer){
    let loc = gesture.location(in: self.view)
    let selectedView = gesture.view
    selectedView?.center = loc
}