我正在学习自动布局,我使用snapkit。我写了一些代码,但工作方式与预期不同。我编写了代码leftMargin,但它的工作方式就好像是一个rightMargin。你可以在照片上看到。我的代码出了什么问题?
我的代码
let container = View()
container.backgroundColor=UIColor.greenColor()
let v1 = View()
v1.backgroundColor=UIColor.blackColor()
self.view.addSubview(container);
container.addSubview(v1)
let padding2 : UIEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
container.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view).offset(padding2.top)
make.bottom.equalTo(self.view).offset(-padding2.bottom)
// make.left.equalTo(self.view).inset(padding2.left)
make.left.equalTo(self.view).offset(padding2.left)
make.right.equalTo(self.view).offset(-padding2.right)
//make.width.equalTo(self.view.bounds.width-90)
/*
make.top.equalTo(self.view).offset(20)
make.left.equalTo(self.view).offset(20)
make.bottom.equalTo(self.view).offset(-20)
make.right.equalTo(self.view).offset(-20)
*/
}
let padding : UIEdgeInsets = UIEdgeInsetsMake(50, 50, 15, 10)
v1.snp_makeConstraints { (make) -> Void in
make.topMargin.equalTo(container).offset(padding.top);
make.leftMargin.equalTo(container).offset(padding.left);
make.width.equalTo(100);
make.height.equalTo(100);
}
答案 0 :(得分:1)
替换
make.topMargin.equalTo(container).offset(padding.top);
make.leftMargin.equalTo(container).offset(padding.left);
与
make.top.equalTo(container).offset(padding.top);
make.left.equalTo(container).offset(padding.left);
left
和 leftMargin
的区别?检查一下:https://stackoverflow.com/a/28692783/3331750
答案 1 :(得分:1)
我从未使用过snapkit,但在常规自动布局中,您可以通过以下方式实现您想要的效果。
let container = UIView()
container.backgroundColor=UIColor.greenColor()
let v1 = UIView()
v1.backgroundColor=UIColor.blackColor()
self.view.addSubview(container)
container.addSubview(v1)
// enable the views to be resized by auto layout
container.translatesAutoresizingMaskIntoConstraints = false
v1.translatesAutoresizingMaskIntoConstraints = false
// pin the container to all edges of the main view
container.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true
container.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor).active = true
container.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
container.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
// anchor the v1 subview to the
v1.topAnchor.constraintEqualToAnchor(container.topAnchor, constant: 20).active = true
v1.leadingAnchor.constraintEqualToAnchor(container.leadingAnchor, constant: 20).active = true
// set a fixed height and width
v1.heightAnchor.constraintEqualToConstant(100).active = true
v1.widthAnchor.constraintEqualToConstant(100).active = true
并且对于比例高度和宽度,用以下代码替换最后两行代码:
v1.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 0.25).active = true
v1.heightAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 0.25).active = true