编程自动布局快速 [英] Programming autolayout swift
问题描述
我在应用程序中拥有:TextView和TableView.我在代码中创建它们.现在,我需要使编程自动布局.但是我不知道它是如何产生的.请帮忙. P.S.对不起,我的英语=)
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()
推荐答案
快速的自动版式指南
文档: https://developer.apple.com/库/内容/文档/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.
一些关键字:
领先:表示对象的左侧部分
Leading: Means the left part of the object
跟踪:表示对象的右侧部分
Trailing: Means the right part of an object
首先,您需要制作所有必要的变量来保存自动布局指南,对于要使用自动布局的视图,您需要将 translatesAutoresizingMaskIntoConstraints 设置为false,
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!
我只是复制了我在项目中使用过的一些代码,但我认为您最终会掌握它的. self.userLocationBtn 只是我想放置在我已继承的UIView中的视图中的按钮.
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.
这篇关于编程自动布局快速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!