我是新手,很快就尝试创建一个输入字段。我的问题是,我想要一个标签,如图所示:
到目前为止,我正在使用StackViews:一个垂直的用于输入字段,三个水平的用于标题和用户输入。到目前为止,我的代码如下:
// Initialize outter stackview
let feedbackOutterSV = UIStackView()
view.addSubview(feedbackOutterSV)
feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
NSLayoutConstraint.activate([
feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
])
// Initalize inner stackview for title
let feedbackInnerSVTitle = UIStackView()
feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
feedbackInnerSVTitle.axis = .horizontal
feedbackInnerSVTitle.alignment = .fill
feedbackInnerSVTitle.distribution = .fillProportionally
let titleLabel = UILabel()
feedbackInnerSVTitle.addArrangedSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = "feedback.input.title".localize()
titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
titleLabel.textColor = .gray
let titleTextView = UITextView()
feedbackInnerSVTitle.addArrangedSubview(titleTextView)
titleTextView.translatesAutoresizingMaskIntoConstraints = false
titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
titleTextView.isScrollEnabled = false
NSLayoutConstraint.activate([
titleLabel.widthAnchor.constraint(equalToConstant: 39)
])
此代码提供了预期的英语输出,但是我必须用不同的语言来实现它,所以我不能使用固定宽度。
谁能告诉我如何更改代码,所以我不需要常量约束,但Label的宽度已调整为单词的长度?
预先感谢
答案 0 :(得分:2)
耦合事物...
我假设您希望“标题标签”与textView高度对齐,因此将.fill
更改为.top
:
feedbackInnerSVTitle.alignment = .top // .fill
并且不要使用.fillProportionally
feedbackInnerSVTitle.distribution = .fill // .fillProportionally
现在,您可能会看到每个元素占用宽度的50%,因此请更改标题标签的content hugging
优先级:
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
,最后, 不要 在标题标签上设置宽度限制:
// NSLayoutConstraint.activate([
// titleLabel.widthAnchor.constraint(equalToConstant: 39)
// ])
结果:
答案 1 :(得分:1)
我认为您可以使用NSLayoutConstraint.activate([
titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0)]
使其随内容而变
答案 2 :(得分:1)
在您的代码中,必须将width constraint
上的titleLabel
设置为titleLabel.intrinsicContentSize.width
NSLayoutConstraint.activate([
titleLabel.widthAnchor.constraint(equalToConstant: titleLabel.intrinsicContentSize.width)
])
还要将distribution
的{{1}}设置为feedbackInnerSVTitle
.fill