0

I currently have a controller with three different views (top, center and bottom). I would like to add several small textfields/boxes to the center area (kind of like the ones they use for a pin code). My current problem is that I need as many textfields as the amount of characters of a word I send to this view.

For example: if the word is "four", I need four textfields and if the word is "seven", I need five.

My idea was to create an array of textFields, loop through the word to count the amount of characters, and then fill the array. I think my code below does at least that, but now I want to add these small textfields to the centerView using anchors.

How can I add these boxes to the view so that they are horizontally displayed?

var arrayOfTextFields: [UITextField] = []

var game: Game? {
    didSet {

      if var answerContent = game?.answer {

            for char in answerContent.characters {

                let count = answerContent.characters.count

                for _ in 1...count {
                    let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 40, height: 60))
                    self.arrayOfTextFields.append(myTextField)

                    answerContent = answerContent.replacingOccurrences(of: "\(char)", with: "_")
                }
            }
      }

   }
}

My centerView:

func createCenterView() -> UIView {
    let centerView = UIView()
    centerView.backgroundColor = Constants.MAIN_THEME_COLOR
    centerView.translatesAutoresizingMaskIntoConstraints = false

    return centerView
}
4
  • Give each text field its own proper frame instead of making them all the same. Commented Apr 21, 2017 at 15:04
  • Set the coordinates of your CGRect to depend on i: CGRect(x: i * width, y: top, width: width, height: height). Probably you'll want to wrap if it doesn't fit horizontally. Then loop through them and add them as subView to your centerView. Commented Apr 21, 2017 at 15:08
  • 1
    A horizontal stackview would work well. You just add as many textfields as you need. Commented Apr 21, 2017 at 15:12
  • Thanks! I will try to use your tips and fix my code. Commented Apr 21, 2017 at 15:20

1 Answer 1

1

Create an array of views of uncertain count

In swift, there's no need to use loop.

let text = "seven"
let views = (0..<text.characters.count).map{ _ in UITextField(frame:.zero) }

Arrange these views horizontally

use UIStackView, or any other 3rd party StackView that support iOS 9 below.

or other layout system like Flexbox (SwiftBox)

or use UICollectionView.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the clarification regarding the loop. Your version is a lot cleaner. I will add it to my code and try to add the views using a UIStackView.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.