在我的viewController
中,我有6个视图。
顶视图是源视图,底视图是目标视图。
我想在源视图以及目标视图上添加随机化器。
我想随机改变视角。因此,请给我任何解决方案。
我想随机滑动源视图和目标视图的位置。
下面是我的代码...
@IBOutlet weak var circle_source: UIView!
@IBOutlet weak var circle_destination: UIView!
@IBOutlet weak var square_source: UIView!
@IBOutlet weak var square_destination: UIView!
@IBOutlet weak var triangle_source: UIView!
@IBOutlet weak var triangle_destination: UIView!
答案 0 :(得分:1)
class VC: UIViewController {
@IBOutlet weak var circle_source: UIView!
@IBOutlet weak var circle_destination: UIView!
@IBOutlet weak var square_source: UIView!
@IBOutlet weak var square_destination: UIView!
@IBOutlet weak var triangle_source: UIView!
@IBOutlet weak var triangle_destination: UIView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let allViews = [circle_source, circle_destination, square_source, square_destination, triangle_source, triangle_destination].compactMap { $0 }
let positions = allViews.map { $0.frame.origin }.shuffled() // randomize all posible positions
positions.enumerated().forEach { (index, position) in
allViews[index].frame.origin = position
}
}
}
extension Array {
func shuffled() -> [Element] {
var results = [Element]()
var indexes = (0 ..< count).map { $0 }
while indexes.count > 0 {
let indexOfIndexes = Int(arc4random_uniform(UInt32(indexes.count)))
let index = indexes[indexOfIndexes]
results.append(self[index])
indexes.remove(at: indexOfIndexes)
}
return results
}
}