Subclass UIImageView layoutSubviews() vs. init()



我发现了一个问题,即对layoutSubviews((的重复调用,其中我创建了我的子视图(UIImageView(并附加了必要的动画,导致动画不断重复而无法停止它们。因此,有必要找到另一种方法来实现子视图的创建和动画的附加。

显而易见的事情是移动布局Subviews((代码

override func layoutSubviews() {
super.layoutSubviews()
print("layoutSubviews()")
spindleLeft = addSpindle(index: 1, posX: 505, posY: 350)
spindleRight = addSpindle(index: 2, posX: 1610, posY: 350)
spinSpindle(spindle: spindleLeft)
spinSpindle(spindle: spindleRight)
}

到初始化

init(cassetteType: CassetteType) {
self.cassetteType = cassetteType
super.init(image: UIImage(named: self.cassetteType.rawValue + "Cassette"))
self.translatesAutoresizingMaskIntoConstraints = false
self.isUserInteractionEnabled = true
self.contentMode = .scaleAspectFit
print("init(cassetteType:)")
spindleLeft = addSpindle(index: 1, posX: 505, posY: 350)
spindleRight = addSpindle(index: 2, posX: 1610, posY: 350)
spinSpindle(spindle: spindleLeft)
spinSpindle(spindle: spindleRight)
}

但是,当我这样做时,主轴子视图不再显示。它们似乎已创建并应用了动画,但它们不再可见。

为什么会这样呢?布局子视图和初始化在这方面有何不同?

addSpindle(( 代码创建每个子视图,如下所示:

func addSpindle(index: Int, posX: CGFloat, posY: CGFloat) -> UIImageView {
let cassetteBounds = self.bounds
let cassetteWidth = cassetteBounds.width
let cassetteHeight = cassetteBounds.height
let cassetteImageWidth =  self.image!.size.width
let cassetteImageHeight = self.image!.size.height
var scale = cassetteWidth / cassetteImageWidth
var spindleWidth = cassetteWidth
var spindleHeight = cassetteImageHeight*scale
var spindleX = 0 as CGFloat
var spindleY = (cassetteHeight - spindleHeight)/2
if spindleHeight > cassetteHeight {
scale = cassetteHeight / cassetteImageHeight
spindleHeight = cassetteHeight
spindleWidth = cassetteImageWidth*scale
spindleY = 0 as CGFloat
spindleX = (cassetteWidth - spindleWidth)/2
}
let spindle = UIImageView(image: UIImage(named: self.cassetteType.rawValue + "Spindle"))
self.addSubview(spindle)
spindle.frame.origin.x = spindleX + (posX*scale)
spindle.frame.origin.y = spindleY + (posY*scale)
spindle.frame.size.width = spindle.image!.size.width*scale //299.0
spindle.frame.size.height = spindle.image!.size.height*scale //299.0
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
gesture.numberOfTouchesRequired = 1
gesture.minimumPressDuration = 0
spindle.isUserInteractionEnabled = true
spindle.isExclusiveTouch = true
spindle.tag = index
spindle.addGestureRecognizer(gesture)
return spindle
}

你在addSpindle方法中使用了self.bounds。由于视图尚未在 init 上布局,因此尚未确定其边界。

您可以在 init 上创建心轴视图,但在计算父项边界时,需要在布局子视图上设置它们的框架。

相关内容

  • 没有找到相关文章

最新更新