gpt4 book ai didi

ios - 在 StackView 中的 UIImage 上添加 UILabel

转载 作者:行者123 更新时间:2023-11-29 00:02:45 25 4
gpt4 key购买 nike

enter image description here

enter image description here

我的 Storyboard部分看起来像第一张照片。在第二张照片上,我提出了限制条件。我想要实现的是将 UILabel 放在 UIImageView 的底部(照片为“DJI_0049”)。

最佳答案

将标签添加到与 UIStackView 相同的 View 中。这样它们就是兄弟/相邻 View 。将imageView添加到stackView,然后将label约束到imageView。

既然他们是 sibling ,那就行了。请注意,标签不能是 stackView 的排列 subview 。否则将导致破坏约束。

例子:

//
// ViewController.swift
// TestSO
//
// Created by Brandon on 2018-02-28.
// Copyright © 2018 XIO. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let label = UILabel()
let imageView = UIImageView()
let otherView = UIView()
let otherView2 = UIView()

let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fill

self.view.addSubview(stackView)
self.view.addSubview(label)
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(otherView)
stackView.addArrangedSubview(otherView2)


label.text = "Hello World"
label.textColor = UIColor.white
imageView.backgroundColor = UIColor.purple
otherView.backgroundColor = UIColor.red
otherView2.backgroundColor = UIColor.blue

stackView.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
stackView.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor),
stackView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor),
stackView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
stackView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])

NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: imageView.centerXAnchor),
label.centerYAnchor.constraint(equalTo: imageView.centerYAnchor),
label.leftAnchor.constraint(greaterThanOrEqualTo: imageView.leftAnchor),
label.rightAnchor.constraint(lessThanOrEqualTo: imageView.rightAnchor),
label.topAnchor.constraint(greaterThanOrEqualTo: imageView.topAnchor),
label.bottomAnchor.constraint(lessThanOrEqualTo: imageView.bottomAnchor)
])


NSLayoutConstraint.activate([
imageView.heightAnchor.constraint(equalToConstant: 100.0),
otherView.heightAnchor.constraint(equalToConstant: 100.0),
otherView2.heightAnchor.constraint(equalToConstant: 100.0)
])
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

关于ios - 在 StackView 中的 UIImage 上添加 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com