如何使用SWIFT以编程方式添加约束

如何使用SWIFT以编程方式添加约束

从上周开始,我一直在努力解决这个问题,但没有更进一步。好吧,所以我需要申请一些约束 以编程方式在……里面斯威夫特转到UIView使用此代码:


var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100));

new_view.backgroundColor = UIColor.redColor();

view.addSubview(new_view);


var constX:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);

self.view.addConstraint(constX);


var constY:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0);

self.view.addConstraint(constY);


var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0);

self.view.addConstraint(constW);


var constH:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0);

self.view.addConstraint(constH);





FFIVE
浏览 875回答 3
3回答

慕姐8265434

如果你想填满你的超级视图,那么我建议你用旋转的方式:    view.translatesAutoresizingMaskIntoConstraints = false     let attributes: [NSLayoutAttribute] = [.top, .bottom, .right, .left]     NSLayoutConstraint.activate(attributes.map {         NSLayoutConstraint(item: view, attribute: $0, relatedBy: .equal, toItem: view.superview, attribute: $0, multiplier: 1, constant: 0)     })另外,如果您需要非相等的约束,请查看iOS 9中的NSLayoutAnchor。直接使用NSLayoutConstraint通常要容易得多:    view.translatesAutoresizingMaskIntoConstraints = false     view.topAnchor.constraint(equalTo: view.superview!.topAnchor).isActive = true     view.bottomAnchor.constraint(equalTo: view.superview!.bottomAnchor).isActive = true     view.leadingAnchor.constraint(equalTo: view.superview!.leadingAnchor, constant: 10).isActive = true     view.trailingAnchor.constraint(equalTo: view.superview!.trailingAnchor, constant: 10).isActive = true
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS