我发现了一个问题,即重复调用layoutSubviews()(在其中创建了UIImageView的子视图并附加了必要的动画),导致动画不断重复而无法停止它们的可能性。因此,有必要找到另一种方法来实现子视图的创建和动画的附加。
显而易见的事情是移动layoutSubviews()代码
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)
}
但是,当我这样做时,主轴子视图不再显示。它们似乎确实已经创建并且已经应用了动画,但是它们不再可见。
为什么会这样呢?在这方面layoutSubviews和init有何不同?
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上创建主轴视图,但是在计算父级边界时,需要在layoutSubviews上设置其框架。
关于ios - 子类UIImageView layoutSubviews()与init(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59778834/