Search code examples
swiftuiviewcontrollerconstraintsios9

IOS9 programmatically constraints for iphone and ipad


In view controller i have created uitextfield programmatically. For this textField I would like to have the following constraints: 90 pixel from top, 50 pixel for height, 8 pixels from right and left sides for iphone devices (so the width is adjusted) and 400 pixel fixed width in case of ipad devices.

Here is the part of my code where these constraints are specified:

text.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
text.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
text.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true
text.heightAnchor.constraint(equalToConstant: 50).isActive = true

This code provide right result for iphone devices, however for ipad devices it is not what I want to get (the width of text field is adjusted). I understand that the block of code is not correct for ipad.

My question is how can i set the constraints programmatically for iphone and ipad devices for the logics described above?

I think the possible solution might be to check screen size width before setting constraints, but I don't know is it proper solution for this task.


Solution

  • 8 pixels from right and left sides for iphone devices (so the width is adjusted) and 400 pixel fixed width in case of ipad devices

    First, let's notice that for iPad your constraints are insufficiently specified, as you are not saying where the x-origin of the view should be on iPad. So, for purposes of discussion, I will have to make something up: I'll say that you want the view horizontally centered.

    So, having stipulated that, all you have to do is look at the traitCollection and examine its userInterfaceIdiom. This tells you whether we are on iPad or iPhone (.pad or .phone), and a simple if/else construct will allow you to supply the appropriate set of constraints.

    So, without my actually writing the constraints for you, here's the structure you'll use:

    text.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
    text.heightAnchor.constraint(equalToConstant: 50).isActive = true
    let dev = self.traitCollection.userInterfaceIdiom
    if dev == .phone {
        text.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
        text.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true
    } else {
        text.widthAnchor.constraint...
        text.centerXAnchor.constraint...
    }