![](/img/trans.png)
[英]How to add constraints to UIStackView inside of a UITableViewCell swift programmatically?
[英]How do I add constraints to a programmatically created UIButton placed in a UIStackView
我有一个简单的垂直UIStackView
,在第三UIStackView
视图中,我想放置以编程方式创建的UIButton
。 我可以这样做,但是按钮会扩展到子视图的整个宽度和高度,而不是我在代码中设置的大小。 我已经使用情节UIStackView
创建了UIStackView
,但是我以编程方式添加了此按钮,因此可以更好地控制按钮的外观。
let doThisButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
doThisButton.setTitle("Let's do this.", forState: .Normal)
doThisButton.setTitleShadowColor(UIColor.blackColor(), forState: .Highlighted)
doThisButton.translatesAutoresizingMaskIntoConstraints = false
doThisButton.layer.cornerRadius = 3
doThisButton.layer.backgroundColor = UIColor(hexString: "b7b7b7").CGColor
doThisButton.layer.borderWidth = 0
liftLogStackView.addArrangedSubview(doThisButton)
在Apple的文档中,我找到了UILayoutGuide
,它似乎可能UILayoutGuide
,但现在我不这么认为。 我尝试了这个:
let container = UILayoutGuide()
doThisButton.addLayoutGuide(container)
doThisButton.leadingAnchor.constraintEqualToAnchor(container.leadingAnchor, constant: 8.0).active = true
doThisButton.trailingAnchor.constraintEqualToAnchor(container.trailingAnchor, constant: 8.0).active = true
liftLogStackView.addArrangedSubview(doThisButton)
container.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
没什么区别。
许多SO搜索并没有针对我的问题提供任何答案,因此我希望有人可以提供帮助。 提前致谢。
您需要更改UIStackView
的对齐方式。 默认情况下已设置,因此子视图将填充垂直于轴的尺寸。 在你的情况下,宽度。
liftLogStackView.alignment = .center
这将应用于UIStackView
所有子视图,而这可能并不是您想要的。 在这种情况下,只需将按钮添加为另一个UIView
的子视图,然后将该视图添加到UIStackView
。 这样,您的新视图将变为全角,但是您可以将按钮限制为所需的任何大小。
另外,我建议阅读UIStackView
文档 。 那里有很多关于如何设置布局的有用信息。
另一个解决方案是将该UIButton
打包到UIView
。 然后, UIView
将伸展并占据所有需要的位置。 UIButton
将保持您定义的大小。 现在,您可以根据容器视图定义约束。
我做了一个简短的Playground示例:
import UIKit
import PlaygroundSupport
class TestViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Test"
self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
self.view.backgroundColor = UIColor.brown
let stackview = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
stackview.axis = .vertical
stackview.distribution = UIStackViewDistribution.fillEqually
let text = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
text.text = "Hello, i am a label"
text.backgroundColor = UIColor.green
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
containerView.backgroundColor = UIColor.red
containerView.addSubview(text)
stackview.addArrangedSubview(containerView)
let text2 = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
text2.text = "Hello, i am another label"
text2.backgroundColor = UIColor.orange
stackview.addArrangedSubview(text2)
self.view.addSubview(stackview)
}
}
let testController = TestViewController()
PlaygroundPage.current.liveView = testController.view
testController
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.