如何在快速按下按钮时添加独立的 UIView?

Posted

技术标签:

【中文标题】如何在快速按下按钮时添加独立的 UIView?【英文标题】:How to add an independent UIView on button press in swift? 【发布时间】:2018-02-13 05:22:23 【问题描述】:

我正在尝试在按下按钮时添加 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



我的视图控制器:

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 手势识别器的子类。我只会发布 LongPress,因为 UIPan 完全相同 - 只是继承自 UIPan 而不是 UILongPress。

import Foundation
import UIKit
class myLongPress: UILongPressGestureRecognizer

var quizItem = UIView()


【问题讨论】:

每次设置gestureRecog.quizItem 即gestureRecog.quizItem = randLabel 的quizitem 都会被替换,如果你调用gestureRecog.quizItem = randTextField,那么quizitem 就会变成文本字段 您没有实例化 QuizItem 来创建对象。您只是在调用 QuizItem 及其函数。 【参考方案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

【讨论】:

工作就像一个魅力。谢谢!

以上是关于如何在快速按下按钮时添加独立的 UIView?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ViewController 及其 NavigationController 上添加 UIview

如何添加HUD? (iOS)

按下按钮时如何更改颜色视图? (迅速)

每次调用 Func 时都会重写 UIView

如何快速按下按钮在 Xcode 上生成声音?

快速点击按钮时添加行或文本字段