Programming autolayout swift

偶尔善良 提交于 2019-12-24 09:40:10

问题


I have in app: TextView and TableView. I create their in code. And now I need to make programming autolayout. But I don't know how it make. Please help. P.S. Sorry for my English =)

    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height

    myTextView = UITextView(frame: CGRect(x: 0, y: 20, width: displayWidth, height: displayHeight / 3))
    creatTextView()

    myTableView = UITableView(frame: CGRect(x: 0, y: displayHeight / 3, width: displayWidth, height: displayHeight * 2 / 3))
    createTable()

回答1:


A quick AutoLayout guide

Documentation: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/

I usually set up constraints to the left, right, bottom/top and width/height constraints. That can be achieved in multiple ways.

Some keywords:

Leading: Means the left part of the object

Trailing: Means the right part of an object

First you want to make all the necessary variables to hold your autolayout guides and for the view you are using autolayout on you'll need to set translatesAutoresizingMaskIntoConstraints to false like this:

self.btn.translatesAutoresizingMaskIntoConstraints = false

var btnLeading: NSLayoutConstraint!
var btnBottom: NSLayoutConstraint!
var btnTop: NSLayoutConstraint!
var btnWidth: NSLayoutConstraint!

I just copied some code I used in a project, but I think you'll get the hang of it eventually. self.userLocationBtn is just a button in my view I want to position in a UIView I have subclassed.

self.btnLeading = NSLayoutConstraint(
        item: self.userLocationBtn,
        attribute: .leading,
        relatedBy: .equal,
        toItem: self,
        attribute: .leading,
        multiplier: 1.0,
        constant: 5.0)
    self.btnBottom = NSLayoutConstraint(
        item: self.userLocationBtn,
        attribute: .bottom,
        relatedBy: .equal,
        toItem: self,
        attribute: .bottom,
        multiplier: 1.0,
        constant: 0.0)
    self.btnTop = NSLayoutConstraint(
        item: self.userLocationBtn,
        attribute: .top,
        relatedBy: .equal,
        toItem: self,
        attribute: .top,
        multiplier: 1.0,
        constant: 0.0)
    self.btnWidth = NSLayoutConstraint(
        item: self.userLocationBtn,
        attribute: .width,
        relatedBy: .equal,
        toItem: self,
        attribute: .height,
        multiplier: 1.0,
        constant: 0.0)

    self.addSubview(self.doneButton)

After the view is added we need to activate the constraints and then update the view.

NSLayoutConstraint.activate([self.btnLeading, self.btnBottom, self.btnTop, self.btnWidth])

self.view.layoutIfNeeded() //Lays out the subviews immediately.


来源:https://stackoverflow.com/questions/42392072/programming-autolayout-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!