将文本显示为 swift 中的书页

Display text as book pages in swift

我正在尝试在 swift 中制作一个 epub reader 应用程序。我解析一个 epub 文件并获取所有元数据和 xhtml。然后,如果用户想要阅读这本书,我会将这本书的所有文本附加到 uitextview。是否有任何可能的解决方案可以像 ios 中的本机图书应用程序那样在书页(而不是滚动视图)中显示文本?

请在您的 post 中加入 minimal, reproducible example。也就是说,以下是 Apple 用于翻页的书籍格式示例。

class ViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
    let viewControllers: [UIViewController] = {
        var viewControllers = [ContentViewController]()
        for index in 1...10 {
            let textView = UITextView()
            textView.text = "Page \(index)"
            let contentVC = ContentViewController(textView: textView)
            viewControllers.append(contentVC)
        }
        return viewControllers
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let pageVC = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
        pageVC.dataSource = self
        pageVC.delegate = self
        pageVC.setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil)

        addChild(pageVC)
        self.view.addSubview(pageVC.view)
        pageVC.view.frame = self.view.bounds
        pageVC.didMove(toParent: self)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard var index = viewControllers.firstIndex(of: viewController), index > 0 else { return nil }
        index -= 1
        return viewControllers[index]
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard var index = viewControllers.firstIndex(of: viewController), index < viewControllers.count else { return nil }
        index += 1
        return viewControllers[index]
    }
}

class ContentViewController: UIViewController {
    var textView = UITextView()
    init(textView: UITextView) {
        self.textView = textView
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        self.view.addSubview(textView)
        self.textView.bounds = self.view.frame
    }
}

至于解析 ePub,你必须解压缩并解析 XML。