创建一个自定义视图并在情节提要中使用它

时间:2018-08-14 10:24:53

标签: swift uiview

我创建了一个自定义视图,该视图可以在情节提要中使用或以编程方式添加:

@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进行运行。

它看起来像这样:

enter image description here

以及类似的模拟器上

enter image description here

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

1 个答案:

答案 0 :(得分:2)

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

imgView.translatesAutoresizingMaskIntoConstraints = false