beefjerky8805
beefjerky8805

Reputation: 13

Black border around PDF in UIWebView, how to remove with Swift

I am writing an IOS8 app in Swift. I am getting a black border around my PDF when it loads in UIWebView. There is a write up on how to fix it, but I have struggled with converting this into Swift. Here's my code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.hidesBarsOnTap = true      
    var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(myArray[0], ofType: "pdf")!)        
    var request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
}

And here is the objective C code from this link that is supposed to fix the black border issue. This goes in webViewDidFinishLoad:

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
[self performSelector:@selector(clearBackground) withObject:nil afterDelay:0.1];}

And this is the function it calls:

- (void)clearBackground {
UIView *v = webVw;
while (v) {
    //v.backgroundColor = [UIColor whiteColor];
    v = [v.subviews firstObject];

    if ([NSStringFromClass([v class]) isEqualToString:@"UIWebPDFView"]) {
        [v setBackgroundColor:[UIColor whiteColor]];

        // background set to white so fade view in and exit
        [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             webVw.alpha = 1.0;
                         }
                         completion:nil];
        return;
    }
}  }

I have almost no experience with objective C, and I'm not sure even where to start converting this to Swift. If I could just be pointed in the right direction on converting this, or if anyone has written a Swift app with code that fixes this issue that they would let me use, it would be greatly appreciated!

Upvotes: 1

Views: 2788

Answers (1)

user4370836
user4370836

Reputation: 26

I think that your suggested solution is not enough even in Objective-C. Please see Rendering PDF in UIWebView iOS 8, causes a black border around PDF.

And , I fixed this issue in Swift. Put below code into the main UIViewController.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    clearPDFBackground(self.webView)
}

func clearPDFBackground(webView: UIWebView) {
    var view :UIView?
    view = webView as UIView

    while view? != nil {
        if NSStringFromClass(view?.dynamicType) == "UIWebPDFView" {
            view?.backgroundColor = UIColor.clearColor()
        }

        view = view?.subviews.first as UIView?
    }
}

Upvotes: 1

Related Questions