如何在 OS X 上制作一个圆角的 WKWebView?

How to make a rounded-corner WKWebView on OS X?

如何在OS X 上制作一个圆角的WKWebView?

之前用NSWebView,我们可以通过layer来实现:

webView.wantsLayer = YES;
webView.layer.cornerRadius = 5;
webView.layer.masksToBounds = YES;

但在 WKWebView 上它不再有效。

图层不对其下方的细节执行隐式遮罩。要遮盖角落,您应该在代码中添加以下内容:

webView.layer.masksToBounds = YES;

来自 CALayer 的文档:

When the value of this property is YES, Core Animation creates an implicit clipping mask that matches the bounds of the layer and includes any corner radius effects.

The default value of this property is NO.

我使用了以下简单的示例代码,它显示了圆角:

- (void)windowDidLoad {
    [super windowDidLoad];
    WKWebView *wv = [[WKWebView alloc] initWithFrame:self.containerView.bounds
                                       configuration:[[WKWebViewConfiguration alloc] init]];
    wv.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
    [self.containerView addSubview:wv];
    wv.wantsLayer = YES;
    wv.layer.cornerRadius = 50;
    wv.layer.masksToBounds = YES;

    [wv loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://whosebug.com"]]];
}