首页 > 解决方案 > 创建一个自定义视图并在情节提要中使用它

问题描述

我创建了一个可以在故事板中使用或以编程方式添加的自定义视图:

@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.

它看起来像这样:

在此处输入图像描述

在这样的模拟器上:

在此处输入图像描述

为什么视图尺寸是设计尺寸而不是实际尺寸?如何获得视图的实际大小?

标签: swiftuiview

解决方案


使用约束应将 translatesAutoresizingmaskintoconstraint 属性设置为 false。在添加为子视图之前尝试放置此代码。

imgView.translatesAutoresizingMaskIntoConstraints = false

推荐阅读