我有UIButton
的子类,它通过使用NSLayoutConstraints
定义了它内部的高度,我需要通过将它 Package 到UIViewRepresentable
中来在SwiftUI
视图中重用它。
代码如下:
struct TestView: View {
var body: some View {
TestButtonWrapper()
.background(Color.red)
}
}
final class TestButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setup() {
translatesAutoresizingMaskIntoConstraints = false
setTitle("Hello", for: .normal)
// these are ignored:
heightAnchor.constraint(equalToConstant: 200).isActive = true
widthAnchor.constraint(equalToConstant: 300).isActive = true
}
}
struct TestButtonWrapper: UIViewRepresentable {
func makeUIView(context: Context) -> TestButton {
let view = TestButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.setContentHuggingPriority(.defaultHigh, for: .vertical)
return view
}
func updateUIView(_ uiView: TestButton, context: Context) {
}
}
结果为:
- 重要:**无法从
TestButton
中删除约束并在TestView
中设置框架。此UIKit
按钮正在常规UIKit
屏幕中重用
- 重要:**无法从
如何求解?为什么UIViewRepresentable
忽略其子节点的约束?
1条答案
按热度按时间enyaitl31#
SwiftUI和UIKit的布局约束不相同...
一种方法是在
TestButton
中覆盖intrinsicContentSize
,而不是尝试设置约束。试试看: