繁体   English   中英

隐藏右键n QLPreviewController吗?

[英]Hide right button n QLPreviewController?

我在我的应用程序中使用QLPreviewController子类化,并使用以下代码。

QLPreviewControllerSubClass* preview = [[QLPreviewControllerSubClass alloc] init];
  [self presentViewController:preview
                       animated:YES
                     completion:^()
                    {
                         // do more stuff here
                     }];

我想隐藏右栏按钮。

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self navigationItem].rightBarButtonItems = nil;
}

但它没有隐藏,任何帮助都是可观的

我也在处理同样的问题。

我隐藏了rightBarButton,但是当pdf的加载时间很长时可能会有一些问题。

下面是我的过程。

1.制作一个QLPreviewController的子类。

2.添加一个计时器以在类初始化时重复将rightBarButton设置为nil。

_hideRightBarButtonTimmer = [NSTimer scheduledTimerWithTimeInterval:0.01
                                                                 target:self
                                                               selector:@selector(hideRightButton)
                                                               userInfo:nil
                                                                repeats:YES];

3.使viewDidAppear中的计时器无效。

[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(cancelTimmer) userInfo:nil repeats:NO];

我发现在pdf文件的加载完成时,设置了rightBarButton。 如果我们能够检测到事件,则解决方案将变得更加容易和清晰。

希望对您有所帮助。

一个简单的解决方案是将一个虚拟视图添加到当前viewController并将QLPreviewControlle.view添加到虚拟视图。

 previewController = [[QLPreviewController alloc] init];
 previewController.dataSource = self;
 previewController.delegate = self;
 previewController.currentPreviewItemIndex = 0;

[self.ContentView addSubview:previewController.view];



- (IBAction)removeQPView:(id)sender {

    [previewController.view removeFromSuperview];
}

我找到了一种解决方案来禁用( 而不是隐藏QLPreviewControllerrightBarButtonItem

该解决方案在iOS8和iOS9中对我来说效果很好

您只需要QLPreviewController子类并覆盖以下方法,然后使用您的子类而不是原始的QLPreviewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // When coming back from background we make sure the share button on the rightbBarButtonItem is disabled
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.navigationItem.rightBarButtonItem.enabled = NO;
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.navigationItem.rightBarButtonItem.enabled = NO; // Disable the share button
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.navigationItem.rightBarButtonItem.enabled = NO; // Disable the share button
}

快速在iOS 9上进行了测试。

最近不得不解决这个问题,并且找不到隐藏此按钮的方法。 我终于设法使用此stackoverflow帖子中的答案隐藏了正确的共享按钮。

基本上,您想继承QLPreviewController的子类,并在viewWillAppear()函数中调用inspectSubviewForView()函数。 找到包含共享按钮的导航项目后,可以将其删除:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // ** traverse subviews until we find the share button ** //
    inspectSubviewForView(self.view)
}

func inspectSubviewForView(view: UIView) {
    for subview in view.subviews {
        if subview is UINavigationBar {
            // ** Found a Nav bar, check for navigation items. ** //
            let bar = subview as! UINavigationBar

            if bar.items?.count > 0 {
                if let navItem = bar.items?[0] {
                    // ** Found the share button, hide it! ** //
                    hideRightBarItem(navItem)
                }
            }
        }
        if subview.subviews.count > 0 {
            // ** this subview has more subviews! Inspect them! ** //
            inspectSubviewForView(subview)
        }
    }
}

func hideRightBarItem(navigationItem: UINavigationItem) {
    // ** Hide/Remove the Share button ** //
    navigationItem.setRightBarButtonItem(nil, animated: false)
}

来自上述链接的上一个张贴者警告说,由于您正在访问私有API,因此可能无法通过Apple的审查过程,因此使用后果自负! 同样,如果Apple在更高版本的iOS中更新了QLPreviewController,则此代码可能不再起作用。

尽管如此,这是唯一对我有用的解决方案。 我希望它也对您有用!

多亏了Matthew Kostelecky,我能够隐藏“共享”按钮,但我想为具有多个文件的通用应用程序中需要的用户添加一些详细信息。

首先,如果您以模态方式使用QLPreviewController,则Matthew的答案将起作用。 如果您像这样从导航控制器中推送QLPreviewController;

navigationController?.pushViewController(quickLookController, animated: true)

它将无法找到任何NavigationBar或ToolBar。 您应该像这样模态调用QLPreviewController;

presentViewController(quickLookController, animated: true, completion: nil)

另外,如果您正在开发通用应用程序,并且有要播放的文件列表。 将会有另一个按钮(列表按钮);

在iPhone中,如果您有多个文件,则QLPreviewController将创建工具栏以显示“列表按钮”和“共享按钮”,并且这两个工具都将位于工具栏上。
在iPad中,这两个按钮都位于NavigationBar上,没有工具栏。

因此,如果iphone中有多个文件,除了Matthew的答案之外,您还应该搜索toolBar;

 func inspectSubviewForView(view: UIView) {
    for subview in view.subviews {
        if subview is UINavigationBar {
            // ** Found a Nav bar, check for navigation items. ** //
            let bar = subview as! UINavigationBar

            if bar.items?.count > 0 {
                if let navItem = bar.items?[0] {
                    navItem.setRightBarButtonItem(nil, animated: false)
                }
            }
        }
        if subview is UIToolbar {
            // ** Found a Tool bar, check for ToolBar items. ** //
            let bar = subview as! UIToolbar
            if bar.items?.count > 0 {
                if let toolBarItem = bar.items?[0] {
                    toolBarItem.enabled = false
                }
            }
        }

        if subview.subviews.count > 0 {
            // ** this subview has more subviews! Inspect them! ** //
            inspectSubviewForView(subview)
        }
    }
}

这段代码将隐藏iPad上的共享按钮,并禁用iPhone上的共享按钮。

希望它对仍然需要它的人有所帮助。

实现此目的的另一种方法是通过setItems(_:animated:) UIToolbar并重写setItems(_:animated:) 如果要删除全部或仅返回要保留的按钮,则可以返回一个空数组。 这是一个示例PreviewControllerHideBottomButtons

去为QLPreviewController子类化,并使用下面提到的代码,仅对使用Xcode 8.3我有效。

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let firstView = self.childViewControllers.first    {
            for view in firstView.view.subviews    {
                if view.isKind(of: UIToolbar.self) {
                    view.removeFromSuperview()
                }
            }
        }
    }

它简单且运行良好,可以导入quicklook并创建一类QL- 单击此处以获取所有您需要的结果,运行良好

导入UIKit
导入QuickLook。
类别QLSubclass:QLPreviewController,QLPreviewControllerDataSource {

var p = NSURL()
override func viewDidLoad() {
    super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
    navigationItem.rightBarButtonItems?[0] = UIBarButtonItem()
}
func show(controller: UIViewController, url: NSURL) {
    // Refreshing the view
    p = url
    self.dataSource = self
    self.reloadData()
    // Printing the doc
    if let navController = controller.navigationController {
        navController.pushViewController(self, animated: true)
    }
    else {
        controller.show(self, sender: nil)
    }
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    let doc = p
    return doc
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
    return 1
}

}

然后在您的视图控制器类中

PatternVC类:UIViewController,UIDocumentInteractionControllerDelegate,UINavigationControllerDelegate {

var link = ""
override func viewDidLoad() {
    super.viewDidLoad()
    let url = "YOUR_URL_LINK"
  //check file exist in local or not------
    if  isFileExist(imgURL: url) {
     //Found then show
        let loadPath = loadDataFromDirectory(imgURL: url)
        showFileWithPath(path: loadPath)
    }else {
        //save in local
        saveDataOnDocumentDirectory(imgURL: url)
    }
}
override func viewDidLayoutSubviews() {
    self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}//Open data
func showFileWithPath(path: String){
    let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
    if isFileFound == true{
        QLSubclass().show(controller: self, url: URL(fileURLWithPath: path) as NSURL)
    }else{}}

还要在视图控制器中添加一个保存在本地的功能-//下载请求-----

private var downloadTask: URLSessionDownloadTask?
func saveDataOnDocumentDirectory(imgURL: String) {
    //let url = URL(string: imgURL)
    let escapedAddress = imgURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    let url2 = URL(string: escapedAddress!)
    let sessionConfig = URLSessionConfiguration.default
    //let sessionConfig = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
    let session: URLSession! = URLSession(configuration: sessionConfig, delegate: self, delegateQueue:  nil)
    downloadTask = session.downloadTask(with: url2!)
    downloadTask?.resume()
    DispatchQueue.main.async {
    }
}}

之后,包含视图扩展PatternVC的扩展:URLSessionDelegate,URLSessionDownloadDelegate {

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {

}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        // lbl.text = "Download failed"
    }
    resetView()
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    let fileManager = FileManager.default
    do {
        let requestURL = downloadTask.currentRequest?.url
        let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:true)
        let fileURL = documentDirectory.appendingPathComponent(getImageNameFromUrl(imgURL: requestURL!))
        do {

            try fileManager.moveItem(at: location, to: fileURL)
            print("save item: \(fileURL)")
        } catch (let writeError) {
            print("Error creating a file \(fileURL) : \(writeError)")
        }
    } catch {
        print(error)
    }
    DispatchQueue.main.async {
        //self.loadDirectory()
        self.resetView()
    }
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    // 1
    //guard let _ = downloadTask.originalRequest?.url, let download = model?.imagePath  else { return }
    let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
    DispatchQueue.main.async {
        //self.radialView.ringProgress = CGFloat(progress * 100)
    }
    print("-URL: \(downloadTask.currentRequest?.url?.relativePath ?? "") ----Per: \(CGFloat(progress * 100))")
}
func resetView() {
    downloadTask!.cancel()
}
func isFileExist(imgURL: String) -> Bool{
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let escapedAddress = imgURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    let url2 = URL(string: escapedAddress!)
    if let pathComponent = url.appendingPathComponent(getImageNameFromUrl(imgURL: url2!)) {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
            return true
        } else {
            print("FILE NOT AVAILABLE")
            let url = APIConstant.videoJpgUrl + link
            //self.loadUrl (urlString:url)
            return false
        }
    } else {
        print("FILE PATH NOT AVAILABLE")
        return false
    }
}
func loadDataFromDirectory(imgURL: String) -> String
{
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let escapedAddress = imgURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    let url2 = URL(string: escapedAddress!)
    if let pathComponent = url.appendingPathComponent(getImageNameFromUrl(imgURL: url2!)) {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
            return filePath
        } else {
            print("FILE NOT AVAILABLE")
            let url = APIConstant.videoJpgUrl + link
            self.loadUrl (urlString:url)
            return filePath
        }
    }else
    {
        return "ERROO"
    }
}
func getImageNameFromUrl(imgURL: URL) -> String{
    let name = imgURL.lastPathComponent
    let result = name.substring(from: name.index(name.startIndex, offsetBy: 5))
    return result
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM