问题
I have:
- UIView (container)
- UIView. subview of (1) - Dark blue in the image below
- UIView. subview of (1) - Purple in the image below
- UILabel. edges.equalToSuperview()
What I'm trying to accomplish:
The thing is, I want the UILabel to be rotated 3pi/2 (270°). Once I've done the rotation, it isn't placed correctly.
This is how it looks like by setting edges.equalToSuperview() and the 270°rotation:
I've tried this (but it leads to a crash):
myLabel.makeConstraints { make in
make.top.equalTo(containerView.snp.left)
make.right.equalTo(containerView.snp.top)
make.left.equalTo(containerView.snp.bottom)
make.bottom.equalTo(containerView.snp.right)
}
The crash description:
*** Terminating app due to uncaught exception 'NSInvalidLayoutConstraintException', reason: 'Constraint improperly relates anchors of incompatible types: <SnapKit.LayoutConstraint:0x6100000ad8c0@MyClass.swift#250 MyProject.MyLabel:0x7fcc2201ca80.top == UIView:0x7fcc2201bd30.left>'
Any ideas what I could do here?
回答1:
I have done it using default autolayout and i like that much too. :)
Here is the function.
func makeLabel() {
//Creating stackview
let stackView = UIStackView()
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.axis = .vertical
//Creating blueView
let blueView = UIView()
blueView.backgroundColor = UIColor.darkGray
blueView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(blueView)
blueView.widthAnchor.constraint(equalToConstant: 100).isActive = true
//Creating purpleView
let purpleView = UIView()
purpleView.backgroundColor = UIColor.purple
purpleView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(purpleView)
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
//Creating rotated label
let label = UILabel()
view.addSubview(label)
label.transform = CGAffineTransform.init(rotationAngle: -CGFloat.pi/2)
label.textColor = UIColor.white
label.text = "This is my Rotated Text"
label.font = UIFont.systemFont(ofSize: 25)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: stackView.centerXAnchor, constant: 0).isActive = true
label.centerYAnchor.constraint(equalTo: stackView.centerYAnchor, constant: 0).isActive = true
}
And here is the output.
Portrait:
Landscape
回答2:
For anyone interested in elk_cloner's answer using Snapkit:
myLabel.snp.makeConstraints { make in
make.centerX.equalTo(containerView.snp.centerX)
make.centerY.equalTo(containerView.snp.centerY)
}
来源:https://stackoverflow.com/questions/44507242/snapkit-and-uilabels-rotation