我正在使用UICollectionView来显示项目。我的单元格包含ImageView并在底部标签中。 当ImageView没有图像时,如何在单元格中心做标签?可以说:
if ("no image in ImageView ") {
ImageView.setActive = false
"what to do here?"
如何居中放置标签?当然我可以设置约束值= cellHeight / 2 但是还有另一种方法吗?还是可以在Xcode编辑器中做到这一点?
答案 0 :(得分:0)
尝试一下。 Swift 4.1
layoutIfNeeded()
使用singleView项目的工作示例(使用按钮进行切换)。相同的代码应在UITableView
或UICollectionView
的单元格内工作。
您将必须在单元格中添加UIStackView
并应用top
,bottom
,left
和right
锚点
在示例中,我使用一个按钮切换视图,可以在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
}
}