swift - 创建一个自定义视图并在情节提要中使用它
问题描述
我创建了一个可以在故事板中使用或以编程方式添加的自定义视图:
@IBDesignable
class PageView: UIView {
}
并覆盖 init 方法并调用commoninit()
以添加一个imageview
作为子视图
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
print(self.bounds)
let imgview = UIImageView(frame: self.bounds)
imgview.contentMode = .scaleAspectFit
imgview.clipsToBounds = true
imgview.backgroundColor = .red
imgview.image = pageImage
addSubview(imgview)
bringSubview(toFront: imgview)
self.pageImageView = imgview
NSLayoutConstraint(item: imgview,attribute: .top,relatedBy: .equal, toItem: self,attribute: .top,multiplier: 1,constant: 0).isActive = true
NSLayoutConstraint(item: imgview,attribute: .leading,relatedBy: .equal,toItem: self,attribute: .leading,multiplier: 1,constant: 0).isActive = true
NSLayoutConstraint(item: self,attribute: .bottom,relatedBy: .equal,toItem: imgview,attribute: .bottom,multiplier: 1,constant: 0).isActive = true
NSLayoutConstraint(item: self,attribute: .trailing,relatedBy: .equal,toItem: imgview,attribute: .trailing,multiplier: 1,constant: 0).isActive = true
self.setNeedsUpdateConstraints()
// add Gesture
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(onLongPress(_:))))
}
在情节提要中使用它后,它是情节提要view.bound
中所选设备大小的大小,而不是我在其上运行的实际设备。为简单起见,我按iPhone 8
尺寸设计并在iphone 8 Plus
.
它看起来像这样:
在这样的模拟器上:
为什么视图尺寸是设计尺寸而不是实际尺寸?如何获得视图的实际大小?
解决方案
使用约束应将 translatesAutoresizingmaskintoconstraint 属性设置为 false。在添加为子视图之前尝试放置此代码。
imgView.translatesAutoresizingMaskIntoConstraints = false
推荐阅读
- java - @slf4j 生成的问题
- javascript - 如何将新的`this`从静态方法传递给静态方法?
- function - 如何对没有显式返回类型的递归函数进行类型检查?
- angular - 即使在活动选项卡上,Angular Material 选项卡也会变灰
- java - 如何使用 Java 9+ 修改 AST
- sas - 使用宏在数据集中按组对列求和
- python - 有没有办法断言两个字符串除了python中的一个部分之外是相同的?
- python - 用另一个相同键行中的非 NA 值填充键控行中的 NA 列值
- python - 我能在下面做什么,我被卡住了?
- talend - 尝试在 Pivtal Cloud FOundry 中部署 Talend Agent 时失败