如何在swift中使用UITextField上的代码来使用约束

时间:2016-01-14 08:17:26

标签: ios xcode swift constraints textfield

我是通过xcode完成的,没有代码,只需用控制键抓取它并选择添加约束,但现在我需要使用代码执行此操作,因此代码如下所示:

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()])
    }
}

我想让我的文本区域水平居中我正在阅读很多关于它但却找不到任何东西

我已经阅读了一些内容并通过这样做解决了这个问题:

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
        ))
}

0 个答案:

没有答案