[UIKit] intrinsicContentSize
intrinsicContentSize를 갖는 경우
UILabel
UIButton
UITextField
UIImageView
UITextView
안 갖는데 헷갈리는 것들
UIStackView
UIVivew
갖는 것 중 주의해야 할 것
UIImageView
-> Image가 없다면 intrinsicContentSize를 갖지 않는다.
-> ImageView의 크기가 아닌 image의 크기를 반환한다.
아래는 테스트 코드
import SnapKit
import Kingfisher
import UIKit
class ViewController: UIViewController {
let button: UIButton = {
let button = UIButton()
button.setTitle("이미지 교체", for: .normal)
return button
}()
let button2: UIButton = {
let button = UIButton()
button.setTitle("디버그 출력", for: .normal)
return button
}()
lazy var textLabel = UILabel()
let stackView = UIStackView()
let scrollView = UIScrollView()
let imageView: UIImageView = {
let view = UIImageView()
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.snp.makeConstraints {
$0.centerX.centerY.equalToSuperview()
$0.height.width.equalTo(300)
}
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .cyan
imageView.kf.setImage(with: URL(string: "https://random.imagecdn.app/300/600"))
view.addSubview(button)
button.snp.makeConstraints {
$0.leading.equalToSuperview()
$0.bottom.equalTo(view.safeAreaLayoutGuide)
}
view.addSubview(button2)
button2.snp.makeConstraints {
$0.trailing.equalToSuperview()
$0.bottom.equalTo(view.safeAreaLayoutGuide)
}
button.addAction(UIAction { [weak self] _ in
let width = Int.random(in: 100...500)
let height = Int.random(in: 100...500)
let url = URL(string: "https://random.imagecdn.app/\(width)/\(height)")
self?.imageView.kf.setImage(with: url)
}, for: .touchUpInside)
button2.addAction(UIAction { [weak self] _ in
guard let self else { return }
print(self.imageView.intrinsicContentSize)
}, for: .touchUpInside)
}
}
UITextField
-> 스크롤이 가능해지는 순간 intrinsicContentSize를 갖지 않는다.