运行代码后,一切正常,除了
setTitle
命令会更改按钮内的文本。我已经尝试了一切,甚至复制了教程,但没有运气。我 2 天前开始使用 Swift,所以任何帮助都会很棒!
CVAimport UIKit
class OnboardingViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
var slides: [OnboardingSlide] = []
var currentPage = 0 {
didSet {
if currentPage == slides.count - 1 {
nextButton.setTitle("GET STARTED", for: .normal)
} else {
nextButton.setTitle("NEXT", for: .normal)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
slides = [
OnboardingSlide(title: "", description: "", image: #imageLiteral(resourceName: "")),
OnboardingSlide(title: "", description: "", image: #imageLiteral(resourceName: "")),
OnboardingSlide(title: "", description: "", image: #imageLiteral(resourceName: "")),
]
pageControl.numberOfPages = slides.count
}
@IBAction func nextButtonClicked(_ sender: UIButton)
{
currentPage += 1
let indexPath = IndexPath(item: currentPage, section: 0)
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
cell.setup(slides[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.width
let currentPage = Int(scrollView.contentOffset.x / width)
pageControl.currentPage = currentPage
}
}
我几乎尝试了所有我能想到的方法,但我是 Swift 的新手,无法弄清楚为什么标题更改对我的标签和文本有效,但对按钮中的文本无效。