Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

ios - Horizontal UIStackView stretching subview

I have the following playground and can't figure out why the ImageView width constraing is not being respected and it fills the remaining space on the StackView

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 800))

let imageView = UIView(frame: CGRect.zero)
imageView.backgroundColor = UIColor.red

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true

let navBarHeaderStackView = UIStackView()
navBarHeaderStackView.distribution = .equalCentering
navBarHeaderStackView.alignment = .center
navBarHeaderStackView.axis = .horizontal
navBarHeaderStackView.addArrangedSubview(imageView)
//navBarHeaderStackView.addArrangedSubview(titlesStackView)

view.addSubview(navBarHeaderStackView)
navBarHeaderStackView.translatesAutoresizingMaskIntoConstraints = false

navBarHeaderStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50).isActive = true
navBarHeaderStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8).isActive = true
navBarHeaderStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
navBarHeaderStackView.heightAnchor.constraint(equalToConstant: 60).isActive = true

navBarHeaderStackView.backgroundColor = UIColor.blue

PlaygroundPage.current.liveView = view

Result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set trailingAnchor to lessThanOrEqualTo insted of equalTo.

navBarHeaderStackView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: 8).isActive = true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...