我想在屏幕上出现新页面时播放声音文件。
到目前为止,我这样做是为了让pageControler
处理一系列图像。
有人可以告诉我我必须在哪里放置代码才能播放声音吗?这样,当sound1
出现在屏幕上时,image1
就会播放。
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var scrollView: UIScrollView!
var images: [String] = ["1", "2", "3", "4", "5"]
var frame = CGRect(x:0,y:0, width:0, height:0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pageControl.numberOfPages = images.count
for index in 0..<images.count {
frame.origin.x = scrollView.frame.size.width * CGFloat(index)
frame.size = scrollView.frame.size
let imgView = UIImageView(frame: frame)
imgView.image = UIImage(named: images[index])
self.scrollView.addSubview(imgView)
}
scrollView.contentSize = CGSize(width:(scrollView.frame.size.width * CGFloat(images.count)), height: scrollView.frame.size.height)
scrollView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
pageControl.currentPage = Int(pageNumber)
}
}
答案 0 :(得分:2)
当所选页面更改时,我没有看到直接拨打电话的方法。您可以在页面视图控制器的setViewControllers(_:direction:animated:completion:)
方法中添加代码,以确定哪个页面处于活动状态并播放适当的声音。
如果使用页面控件,则可能还可以继承UIPageControl的子类,并在currentPage
属性上使用didSet来确定要播放的声音。
只需添加一个新文件,使其成为可可触摸类,并将其作为UIPageControl
的子类即可。将其命名为CustomPageControl
。然后,您的实现可以像这样简单:
导入UIKit
class CustomPageControl: UIPageControl {
override var currentPage: Int {
didSet {
//Your code to play sounds based on selected index could go
//here, or broadcast a notification that your view controller
//would listen for
print("New page index = \(currentPage)")
}
}
}
然后只需在UIPageViewController上选择页面控件,选择“身份检查器”,然后将页面控件的类更改为自定义CustomPageControl
类。完成此操作后,只要您的页面索引发生更改,就会调用上面的didSet方法。