Как изменить переменную UITextView после нажатия на кнопку? - PullRequest
1 голос
/ 20 февраля 2020

Я создаю UITextView со случайным тегом и текстом, но он создается с одной переменной, возможно ли обновить переменную после создания UITextView (нажав кнопку добавления)? Возможно добавьте к нему случайное число, например newText1, newText2 .. et c.

Так что следующее UITextView уже создано с новой переменной?

PS Извините, если вопрос глуп, я только недавно начал изучать Swift

@IBOutlet weak var addTextButton: UIButton!
@IBOutlet weak var StoriesView: UIView!

var newText = UITextView()

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

@IBAction func addTextButton(_ sender: Any) {

        let maxNumber = 10000
        let i = Int(arc4random_uniform(UInt32(maxNumber)))

        newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
         self.StoriesView.addSubview(newText)

         newText.font = UIFont(name: "Verdana", size: 11)
         newText.text = "TAP TO EDIT #\(i)"
         newText.sizeToFit()
         newText.textColor = UIColor.black
         newText.backgroundColor = UIColor.clear
         newText.tag = i

         newText.isEditable = true
         newText.isSelectable = true
         newText.isUserInteractionEnabled = true
         newText.allowsEditingTextAttributes = true
         newText.translatesAutoresizingMaskIntoConstraints = true

         newText.enablesReturnKeyAutomatically = true

         newText.delegate = self       
       }

UPD:

let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        fontToolbar.barStyle = .default
        fontToolbar.items = [
            UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
             UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
             UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
        UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
        fontToolbar.sizeToFit()
        newText.inputAccessoryView = fontToolbar

на панели инструментов над клавиатурой У меня есть кнопки, здесь мы меняем цвет

@objc func redColor() {
        newText.textColor = UIColor.red}

    @objc func blueColor() {
        newText.textColor = UIColor.blue}

    @objc func greenColor() {
        newText.textColor = UIColor.green}

Так что цвет меняется только в недавно созданный UITextView

Ответы [ 2 ]

2 голосов
/ 20 февраля 2020

При нажатии кнопки создайте новый texView и назначьте ему значение тега. После добавления измените значение i на +1, чтобы у каждого добавленного textView было новое значение тега.

var i = 1
var newText = UITextView()

@IBAction func addTextButton(_ sender: Any) {

    newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
     self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.clear
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true

    newText.delegate = self
    //increment i
    i+=1
}

, тогда вы можете получить доступ к своему textField с помощью значений тегов, таких как:

if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
     // textView.text = "change it"   
}

ОБНОВЛЕНИЕ:

Добавьте метод делегирования textView и, как только текстовое представление начнет редактирование, измените значение newText на текущее редактируемое текстовое представление

class ViewController : UIViewController, UITextViewDelegate {

    func textViewDidBeginEditing(_ textView: UITextView) {
        newText = textView
    }
}
1 голос
/ 20 февраля 2020

Я немного изменил ваш код, чтобы иметь новый UITextView объект с нажатием кнопки

import UIKit

class ScannerViewController: UIViewController, UITextViewDelegate {

  @IBOutlet weak var StoriesView: UIView!
  @IBOutlet weak var addTextButton: UIButton!
  var yposition: CGFloat!
  var textFieldTag: [Int]! = []

    override func viewDidLoad() {
    super.viewDidLoad()
    yposition = 20
  }

  @IBAction func addTextButton(_ sender: Any) {

    let xposition = self.StoriesView.frame.origin.x
    let maxNumber = 10000
    let i = Int(arc4random_uniform(UInt32(maxNumber)))
    textFieldTag.append(i)

    let newText = UITextView(frame: CGRect(x: xposition , y: yposition , width: 380, height: 40))
    self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.yellow
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true
    newText.delegate = self

    yposition = yposition + 45
  }

  @IBAction func accessTextFields(_ sender: Any) {

    //access all text fields
    for tag in textFieldTag {
      if let textField = self.StoriesView.viewWithTag(tag) as? UITextView {
        //change properties here
        textField.backgroundColor = .cyan
      }
    }

    //access specific text fields
    if let textField = self.StoriesView.viewWithTag(textFieldTag.first!) as? UITextView {
      //change properties here
      textField.backgroundColor = .orange
    }

    if let textField = self.StoriesView.viewWithTag(textFieldTag[textFieldTag.count - 1]) as? UITextView {
      //change properties here
      textField.backgroundColor = .green
    }
  }
}

Он будет иметь следующий вывод !!

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...