I've done this by xcode without code, just grab it with control key and select add constraint, but now i need to do this using code, so the code looks like this:
class RegistrationViewController: UIViewController, UITextFieldDelegate {
// UserInputs extends UITextField
var firstName: UserInputs!
var lastName: UserInputs!
override func viewDidLoad() {
super.viewDidLoad()
firstName = UserInputs(frame: CGRectMake(75, 150, 230, 40))
lastName = UserInputs(frame: CGRectMake(75, 200, 230, 40))
addPlaceHolder(firstName, name: "Firstname")
addPlaceHolder(lastName, name: "Lastname")
view.addSubview(firstName!)
view.addSubview(lastName!)
}
func addPlaceHolder(textField: UserInputs, name: String){
textField.attributedPlaceholder = NSAttributedString(string: name,
attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
}
}
i want to make my textfields to go center horizontally i'm reading a lot about it but couldn't find anything yet
i've read something and solved it by doing this:
func doThis(textField: UserInputs){
textField.translatesAutoresizingMaskIntoConstraints = false
let bounds = UIScreen.mainScreen().bounds
let width = bounds.size.width
//let height = bounds.size.height
//230 because width of my textField is 230
let left = (width - 230)/2
let right = -((width - 230)/2)
textField.addConstraint(
NSLayoutConstraint(
item: textField,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1.0,
constant: 40
))
//left
self.view.addConstraint(
NSLayoutConstraint(
item: textField,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Leading,
multiplier: 1.0,
constant: left
))
//right
self.view.addConstraint(
NSLayoutConstraint(
item: textField,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1.0,
constant: right
))
//top
self.view.addConstraint(
NSLayoutConstraint(
item: textField,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Top,
multiplier: 1.0,
constant: 300
))
}