Я разрабатываю UIImageView
поверх UICollectionView
, используя ограничения автопоставки:
Я закрепил UIImageView
, чтобы взять верхнюю часть экрана с фиксированным соотношением H: W 4:3, затем позвольте UICollectionView
занять все свободное место внизу.
Странно, но когда я его запустил, представление в xcode simulator сильно отличается от отладчика иерархии представлений:
Отладчик иерархии представлений :
Симулятор iPhone 8 Plus :
В UICollectionView
каждая ячейка будетпокажите фотографию лица, я настроил itemSize of UICollectionView
как квадрат.Затем должно отображаться все лицо (поэтому представление отладчика корректно, а симулятор - нет).
// MARK: - UICollectionViewDelegateFlowLayout
extension ViewController : UICollectionViewDelegateFlowLayout {
// set item size
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
// gw: to force one row, height need to be smaller than flow height
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
}
Что может быть причиной этой разницы ?
Я использую xcode 10.1, ios 12.1 Полный код здесь (не очень длинный):
import UIKit
class ViewController: UICollectionViewController{
let collectionViewCellIdentifier = "MyCollectionViewCellIdentifier"
let canvas:Canvas = {
let canvas = Canvas()
canvas.backgroundColor = UIColor.black
canvas.translatesAutoresizingMaskIntoConstraints=false
canvas.alpha = 0.2
return canvas
} ()
let photoView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(imageLiteralResourceName: "hongjinbao")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
return imageView
} ()
private let myArray: NSArray = ["First","Second","Third"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// stack views
view.addSubview(photoView)
view.addSubview(canvas)
collectionView?.backgroundColor = UIColor.white
collectionView?.translatesAutoresizingMaskIntoConstraints = false
collectionView?.register(PersonCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
setupLayout()
}
private func setupLayout() {
photoView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
photoView.heightAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.333).isActive = true
photoView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
photoView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
canvas.topAnchor.constraint(equalTo: photoView.topAnchor).isActive = true
canvas.bottomAnchor.constraint(equalTo: photoView.bottomAnchor).isActive = true
canvas.leadingAnchor.constraint(equalTo: photoView.leadingAnchor).isActive = true
canvas.trailingAnchor.constraint(equalTo: photoView.trailingAnchor).isActive = true
collectionView?.topAnchor.constraint(equalTo: photoView.bottomAnchor).isActive = true
collectionView?.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
collectionView?.leadingAnchor.constraint(equalTo: photoView.leadingAnchor).isActive = true
collectionView?.trailingAnchor.constraint(equalTo: photoView.trailingAnchor).isActive = true
}
}
// MARK: - UICollectionViewDataSource
extension ViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.collectionViewCellIdentifier, for: indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 13
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension ViewController : UICollectionViewDelegateFlowLayout {
// set item size
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
// gw: to force one row, height need to be smaller than flow height
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
}
import UIKit
class PersonCollectionViewCell: UICollectionViewCell {
let face: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(imageLiteralResourceName: "mary")
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
} ()
let name: UILabel = {
let textLabel = UILabel()
textLabel.translatesAutoresizingMaskIntoConstraints = false
return textLabel
} ()
let desc: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
} ()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
// gw: needed by compiler
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
addSubview(face)
addSubview(name)
addSubview(desc)
backgroundColor = UIColor.red
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0":face]))
}
}