简体   繁体   中英

Why is image view stretching to fill half the width in a UIStackView?

I am taking an UIImageView on the left of the horizontal stack view and a label with number of lines set to 0. The issue is that both the UIImageView and the label are filling equal space even though I have set the stack view distribution property to fill. I don't want my image view to expand. Changing content hugging isn't helping.

Problem is: When telling the stack view to fill the content area it try to do it as best as possible. When setting the distribution type to fill it do not know how to fill. You have to provide this information by setting a width constraint via autolayout for the image. The label will fill the remaining area then.

在此处输入图片说明

Another way of doing this would be to add an invisible spacer object at the right side of the image + label stack.

private func spacer() -> UIView {
    let stretchingView = UIView()
    stretchingView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
    stretchingView.backgroundColor = UIColor.clear
    stretchingView.translatesAutoresizingMaskIntoConstraints = false
    return stretchingView
}

private func labelWithImage() -> UIView {
    let image = UIImage(systemName: "map")
    let imageView = UIImageView(image: image)
    let label = UILabel()
    label.text = "3 Miles Away"
    label.font = UIFont.systemFont(ofSize: 17, weight: .regular)
    label.textColor = UIColor.gray
    let stackView = UIStackView(arrangedSubviews: [imageView, label, spacer()])
    stackView.alignment = .leading
    stackView.axis = .horizontal
    return stackView
}

示例图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM