如果另一个项目不存在,Xcode会将项目对齐在中心

问题描述 投票:0回答:1

我正在使用UICollectionView来显示项目。我的单元格包含ImageView和底部标签。当ImageView没有图像时,如何在单元格的中心制作标签?让我们说:

if ("no image in ImageView ") { 
ImageView.setActive = false
"what to do here?"

如何集中标签?当然我可以设置约束值= cellHeight / 2但是还有另一种方法吗?或者我可以在Xcode编辑器中这样做吗?

ios swift xcode alignment cell
1个回答
0
投票

试试这个。 Swift 4.1

  • 在stackView中添加containerViews(在单元格内)。
  • 将imageViews和标签添加到容器视图中
  • 隐藏其中一个并在stackView中运行layoutIfNeeded()

使用singleView项目的工作示例(使用按钮切换)。相同的代码应该在UITableViewUICollectionView的单元格内部工作。

你将不得不在单元格内添加UIStackView并应用topbottomleftright anchors

在示例中,我使用按钮切换视图,您可以使用imageView中的didSet {}来隐藏/显示containerView

import UIKit
class ViewController: UIViewController {
    var stackView: UIStackView!
    var topView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        topView = UIView()
        topView.backgroundColor = .yellow
        let bottomView = UIView()
        bottomView.backgroundColor = .cyan
        stackView = UIStackView(arrangedSubviews: [topView, bottomView])
        stackView.distribution = .fillEqually
        stackView.axis = .vertical
        self.view.addSubview(stackView)
        stackView.centerWithSize(size: CGSize(width: 100, height: 200))
        let imageView = UIImageView()
        imageView.image = UIImage(named: "hexagon.png")
        topView.addSubview(imageView)
        imageView.centerWithSize(size: CGSize(width: 30, height: 30))
        let label = UILabel()
        label.text = "TEXT"
        label.font = UIFont(name: "Helvetica", size: 20)
        bottomView.addSubview(label)
        label.centerWithSize(size: CGSize(width: 100, height: 100))
        addButton()
    }
    func addButton() {
        let button = UIButton(type: UIButtonType.system) as UIButton
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        button.setTitle("TOGGLE", for: .normal)
        button.addTarget(self, action: #selector(toggle), for: .touchUpInside)
        button.frame = CGRect(x: 0, y: 50, width: 100, height: 30)
        self.view.addSubview(button)
    }
    @objc func toggle(sender: UIButton) {
        topView.isHidden = topView.isHidden == true ? false : true
        stackView.layoutIfNeeded()
    }
} 
extension UIView {
   func centerWithSize(size: CGSize) {
       self.translatesAutoresizingMaskIntoConstraints = false
       self.widthAnchor.constraint(equalToConstant: size.width).isActive = true
       self.heightAnchor.constraint(equalToConstant: size.height).isActive = true
       self.centerXAnchor.constraint(equalTo: self.superview!.centerXAnchor).isActive = true
       self.centerYAnchor.constraint(equalTo: self.superview!.centerYAnchor).isActive = true
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.