我创建了一个自定义视图,可以在故事板中使用或以编程方式添加:
@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
.
看起来是这样的:
在这样的模拟器上:
为什么视图大小是设计大小而不是实际大小?
如何获取视图的实际大小?