首页 > 解决方案 > 使用来自 textviews 数组的 func resign 第一响应者

问题描述

我的代码使用 didTapAdd 函数向视图控制器添加无穷无尽的文本视图。问题是我不能移动它,因为它是一个文本视图。如果它是标签或图像视图,这将完美地工作。不知何故,我想做一个类似于开关 everttime didtapadd2 的事情,我希望所有的文本视图都不能输入,所以我可以移动它们,然后再次调用 func 以将其关闭。

import UIKit
class ViewController: UIViewController {
var addButton = UIButton()
var cutOff = UIButton()
var count: Int = 0
var ht = -90

var arrTextFields = [UITextView]()
override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(addButton);view.addSubview(cutOff)
    cutOff.backgroundColor = .systemPink
    addButton.backgroundColor = .systemOrange
    addButton.frame = CGRect(x: view.bounds.midX - 80, y: view.bounds.midY, width: 50, height: 50)
    cutOff.frame = CGRect(x: view.bounds.midX - 80, y: view.bounds.midY+60, width: 50, height: 50)
    addButton.addTarget(self, action: #selector(didTapAdd), for: .touchUpInside)
    cutOff.addTarget(self, action: #selector(didTapAdd2), for: .touchUpInside)
}

@objc func didTapAdd() {


    let subview = UITextView()

    subview.isUserInteractionEnabled = true
    subview.isMultipleTouchEnabled = true
    arrTextFields.append(subview)
    view.addSubview(subview)
    subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: 50, height: 30)
    subview.backgroundColor = .systemTeal
    subview.tag = count

    let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
    subview.addGestureRecognizer(pan)

    count += 1
    ht += 50

    arrTextFields.append(subview)


}

@objc func didTapAdd2() {


    cutOff.isSelected = !cutOff.isSelected

    arrTextFields.forEach { $0.isScrollEnabled = cutOff.isSelected }


}
@objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
    let draggedView = gesture.view!
    view.bringSubviewToFront(draggedView)
    let translation = gesture.translation(in: view)
    draggedView.center = CGPoint(x: draggedView.center.x + translation.x, y: draggedView.center.y + translation.y)
    gesture.setTranslation(.zero, in: view)
}
}

标签: arraysswiftswitch-statementresignfirstresponderisuserinteractionenabled

解决方案


我有你的代码的解决方案,我希望这是你正在寻找的。

因此,首先创建UITextView下面ht变量的数组,如下所示:

var arrTextFields = [UITextView]()

然后在didTapAdd方法内部添加子视图在数组中,所以在后面添加以下行ht += 50

arrTextFields.append(subview)

现在在didTapAdd2方法内部,编写以下代码

@objc func didTapAdd2() {
    self.view.endEditing(true)
    cutOff.isSelected = !cutOff.isSelected
    arrTextFields.forEach { $0.isScrollEnabled = cutOff.isSelected }
}

我希望这能解决您的问题。


推荐阅读