作者:风中凌乱2602938623 | 来源:互联网 | 2024-11-19 10:27
正在开发一款简单的闪存卡片应用,如下面的示例所示:
目标是实现类似如下的向后滑动手势:
为了达到这一目的,当用户执行向后滑动操作时,需要调用onBack(index: Int)
方法(以便更新显示的卡片):
import UIKit
class FlashCardViewController: UIViewController {
@IBOutlet weak var cardLabel: UILabel!
private let cOntents= ["Lorem", "Ipsum", "Dolor", "Sit"]
private var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
updateCardContent()
}
private func updateCardContent() {
cardLabel.text = contents[currentIndex]
}
@IBAction private func backButtonTapped(_ sender: Any) {
guard currentIndex > 0 else { return }
currentIndex -= 1
updateCardContent()
}
@IBAction private func nextButtonTapped(_ sender: Any) {
guard currentIndex
解决方案
方案一:使用UIScrollView实现滑动效果
如果理解无误,您希望在点击“上一张”或“下一张”按钮时,能够实现卡片之间的滑动切换效果。为此,建议使用UIScrollView
来实现这一功能。具体代码如下:
class FlashCardViewController: UIViewController, UIScrollViewDelegate {
private let cOntents= ["Lorem", "Ipsum", "Dolor", "Sit"]
private let scrollView = UIScrollView()
private var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
setupScrollView()
}
private func setupScrollView() {
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.cOntentSize= CGSize(width: view.bounds.width * CGFloat(contents.count), height: view.bounds.height)
for (index, content) in contents.enumerated() {
let label = UILabel(frame: CGRect(x: view.bounds.width * CGFloat(index), y: 0, width: view.bounds.width, height: view.bounds.height))
label.textAlignment = .center
label.text = content
scrollView.addSubview(label)
}
view.addSubview(scrollView)
}
@IBAction private func backButtonTapped(_ sender: Any) {
guard currentIndex > 0 else { return }
currentIndex -= 1
let offset = CGPoint(x: view.bounds.width * CGFloat(currentIndex), y: 0)
scrollView.setContentOffset(offset, animated: true)
}
@IBAction private func nextButtonTapped(_ sender: Any) {
guard currentIndex
说明:通过创建一个UIScrollView
来实现分页效果,并为每一页添加一个包含contents
数组中对应文本的UILabel
。每当用户滚动到不同页面时,currentIndex
会更新为当前页面的索引。最后,当用户点击“上一张”或“下一张”按钮时,页面会平滑地滚动到前一页或下一页。