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

标签 ios swift xcode uiview

我试图在按下按钮时添加 UILabel 和其他 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
}

}

我的 View Controller :

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()

}

最佳答案

您可以通过如下轻微更改代码来实现:

@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
}

关于ios - 如何在快速按下按钮时添加一个独立的 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759960/

相关文章:

ios - 如何在特定日期前 2 天触发 UserNotifications

ios - 错误 ITMS-90207 bundle 无效

ios - Parse & Swift- 没有匹配查询的结果

ios - Xcode 10.x 中 iOS 纵向和横向的替代布局

iOS 5 - AVCaptureDevice 设置焦点和焦点模式卡住实时相机图片

arrays - 如何迭代函数数组

ios - 检查应用程序更新时读取 json 错误

ios - raywenderlich.com 文章中的设置 CALayer 颜色

ios - NSFetchedResultsController:多个 FRC,更新时出现委托(delegate)错误

iphone - UIPopoverController 前面的 UIImageView