加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift UIStackView:以编程方式从中心定位元素.

发布时间:2020-12-14 04:36:05 所属栏目:百科 来源:网络整理
导读:我试图在UIStackView中获取元素,以便从中心平等地定位自己. 这是我想要的效果: 如您所见,我希望两个文本字段彼此间隔相等,并在堆栈视图中对齐中心. 这个堆栈视图将包含我需要排列的1-7个文本字段. 以下是目前的情况: 这就是我设置文本字段的方式 let textL
我试图在UIStackView中获取元素,以便从中心平等地定位自己.

这是我想要的效果:

enter image description here

如您所见,我希望两个文本字段彼此间隔相等,并在堆栈视图中对齐中心.

这个堆栈视图将包含我需要排列的1-7个文本字段.

以下是目前的情况:

enter image description here

这就是我设置文本字段的方式

let textLabel = UILabel()
textLabel.backgroundColor = UIColor.red
textLabel.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi"
textLabel.textAlignment = .center

let textLabel1 = UILabel()
textLabel1.backgroundColor = UIColor.red
textLabel1.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel1.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel1.text  = "Hi"
textLabel1.textAlignment = .center

我正在生成堆栈视图,如下所示:

//Stack View
let stackView   = UIStackView()
stackView.axis  = UILayoutConstraintAxis.horizontal
stackView.distribution  = UIStackViewDistribution.equalCentering
stackView.alignment = UIStackViewAlignment.fill
stackView.spacing   = 16.0

stackView.addArrangedSubview(textLabel)
stackView.addArrangedSubview(textLabel1)
stackView.translatesAutoresizingMaskIntoConstraints = false;

self.view.addSubview(stackView)

//Constraints

stackView.leftAnchor.constraint(equalTo: self.view.leftAnchor,constant: 50).isActive = true
stackView.rightAnchor.constraint(equalTo: self.view.rightAnchor,constant: -50).isActive = true
stackView.topAnchor.constraint(equalTo: self.view.topAnchor,constant: 100).isActive = true

如何将元素放入对齐中心?

我以为是的

UIStackViewDistribution.equalCentering

然而,这并没有做太多.

感谢你的时间:)

解决方法

多数民众赞成.通常情况下,具有中心对齐和相等居中分布的水平UIStackView应该完全相同:

enter image description here

enter image description here

enter image description here

但也许我不理解你是对的,你真的想要这样的东西:

enter image description here

在这种情况下,您必须选择Fill Equally作为分配方法,并使标签本身居中于其文本:

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读