Reputation: 321
I am trying to show multiple textFields
by running a loop, that whether the number of textfields noTextField
is greater than zero (which is an input value), it should display the multiple textFields on ViewController
.
Here is what I have one textfield and prints multiple hello
but could not display multiple textfields.
What I have
What I want
if self.noTextFields! > 0 {
for _ in 0..<self.noTextFields! {
// self.createForm()
print ("hello")
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
self.view.addSubview(sampleTextField)
}
}
Upvotes: 0
Views: 2307
Reputation: 1199
You just add dynamic value of y(add x if required).
var counter = 30
var yValue = 0
in for loop you just need to add below code
let sampleTextField = UITextField(frame: CGRect(x: 20, y: yValue, width: 300, height: 40))
yValue = Counter
//(space each textfield if 30 because height of textfield is 40)
counter = counter + 70
Upvotes: 0
Reputation: 1149
Mistakes and Corrections:
Your snippet will look like
var xValue = 0,yValue =0
var tagNo = 0
var textObjects = allocate new array.
if self.noTextFields! > 0 {
for _ in 0..<self.noTextFields! {
// self.createForm()
print ("hello")
let sampleTextField = UITextField(frame: CGRect(x: xValue, y: yValue, width: 300, height: 40)) //Note that I have set xValue and yValue
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
sampleTextField.tag = tagNo //Note this line for tagNo
self.view.addSubview(sampleTextField)
textObjects.addObject:sampleTextField //Note this line for adding textfield to array for reference to get total items added
yValue = yValue + sampleTextField.frame.size.height + 20; //Added yValue to place another text view at bottom of initial one and 20px buffer for gap.
}
}
print "Total Textobjects in array:textObjects.count
If required to get object from view its self.view.viewwithTag(tagNo) will return exact text field.
Upvotes: 1