记录寄己走过的路

iOS UIWebViewApple译文

Write in the first


随着HTML5的迅速发展与日趋成熟,越来越多的移动开发者选择使用HTML5来进行混合开发,不仅节约成本而且效果绚丽,只有一个感觉 D!(此时默默下决心我要学会☺)。

那么作为内置浏览器的WebView被重视起来,不管是iOS还是Android,都要是使用 WebView 控件来加载HTML5页面,甚至有些程序打开后只有一个WebView 控件,其他的页面都是被它加载出来网页。
在「时间 & 知识 」有限内,总结的文章难免有「未全、不足 」的地方,还望各位好友指出,以提高文章质量。



正题

在这里首先附上官方原文地址 UIWebView Class

Relationships
Inherits From UIView 继承自: UIView
Conforms To 遵守:CVarArgEquatableHashableEqua NSCoding tableUIAccessibilityIdentificationUIScrollViewDelegate
Framework iOS 2.0+

Class

UIWebView

You can use the UIWebView class to embed web content in your app. To do so, create a UIWebView object, attach it to a window, and send it a request to load web content. You can also use this class to move back and forward in the history of webpages, and you can even set some web content properties programmatically.

你可以使用 UIWebView 类来将网页(web content)嵌入到你的 app 中。为此,首先创建一个 UIWebView 对象,将它添加到一个 窗体(window) 上, 然后给它发送一个请求去加载网页(web content)。你还可以用这个类在网页浏览记录中后退前进(move back and forward),甚至可以设置一些网页属性(web content properties)。

Overview

Note
In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to false if you render files that are not supposed to run JavaScript.

注意:
在只支持iOS 8及以后的系统的 app 中,建议使用WKWebView,而不是 UIWebView 。值得注意的一点是,如果你要渲染的文件不支持运行 JavaScript 的话,不妨将 WKPreferencesjavaScriptEnabled 属性设为 NO。

Important
An iOS app linked on or after iOS 10.0 must include in its Info.plist file the usage description keys for the types of data it needs to access or it will crash. To access a user’s photo data specifically, it must include NSPhotoLibraryUsageDescription and NSCameraUsageDescription.

重要:
iOS应用程序链接或之后的iOS 10.0必须包括在其信息。plist文件使用描述键类型的数据需要访问或它会崩溃。访问用户的照片数据具体地说,它必须包括NSPhotoLibraryUsageDescriptionNSCameraUsageDescription

Use the loadHTMLString(_:baseURL:) method to begin loading local HTML files or the loadRequest(_:) method to begin loading web content. Use the stopLoading() method to stop loading, and the isLoading property to find out if a web view is in the process of loading.

我们可以使用 loadHTMLString:baseURL: 方法来加载本地 HTML 文件或者用 loadRequest: 方法来加载网页(web content)。我们还可以通过调用stopLoading 方法来停止加载,以及通过获取属性 loading 的值来判断一个 web view 是否还处于正在加载的过程中。

If you allow the user to move back and forward through the webpage history, then you can use the goBack() and goForward() methods as actions for buttons. Use the canGoBack and canGoForward properties to disable the buttons when the user can’t move in a direction.

如果你想让用户在浏览网页时可以前进后退,你可以通过 button 的 action 对goBackgoForward 方法的调用来控制。当用户不能在某一个方向“移动”时,需要使用 canGoBackcanGoForward 属性来禁用按钮的前进后退操作。

By default, a web view automatically converts telephone numbers that appear in web content to Phone links. When a Phone link is tapped, the Phone app launches and dials the number. To turn off this default behavior, set the dataDetectorTypes property with a UIDataDetectorTypes bitfield that does not contain the phoneNumber flag.

默认情况下,一个 web view 会自动将网页中的电话号码转成一个号码链接(Phone links)。当用户在点击那个链接(Phone links)时,系统会自动启动 Phone app 并拨打那个电话号码。你可以将属性 dataDetectorTypes 的值设置为一个 UIDataDetectorTypes 位字段来关闭这个电话号码识别行为,因为UIDataDetectorTypes不包括 TypePhoneNumber 这个标志位。

You can also use the scalesPageToFit property to programmatically set the scale of web content the first time it is displayed in a web view. Thereafter, the user can change the scale using gestures.

你可以通过设置 scalesPageToFit 属性来设置网页(web content)第一次展示在一个 web view 中的页面比例。但仅仅这个属性只在首次展示时有效,首次展示之后用户仍然可以通过手势改变页面比例。

Set the delegate property to an object conforming to the UIWebViewDelegate protocol if you want to track the loading of web content.

如果你想追踪网页内容(web content)的加载,你需要将 web view 的 delegate 属性赋给一个遵守 UIWebViewDelegate 协议的对象。

Important
You should not embed UIWebView or UITableView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled.

重要:
不要将 UIWebView 或 UITableView 对象嵌入到 UIScrollView 对象中。如果你这么做了,将会导致一些意想不到的结果,因为那两个嵌套的 view 的 touch 事件会被混淆并且会被错误地处理。

You can easily debug the HTML, CSS, and JavaScript contained inside a UIWebView with Web Inspector. Read Debugging Web Content on iOS to learn how to configure Web Inspector for iOS. Read the rest of Safari Web Content Guide to learn how to create web content that is optimized for Safari on iPhone and iPad.

For information about basic view behaviors, see View Programming Guide for iOS.

借助 Web Inspector,可以很方便地调试一个 UIWebView 中的HTML,CSS 和 JavaScript。你可以通过阅读 Debugging Web Content on iOS 来学习如何配置 Web Inspector for iOS。你还可以通过阅读 Safari Web Content Guide 的其余部分,来学习如何创建一个为 iPhone 和 iPad 上的 Safari 而优化的网页(web content)。

如果你想了解一些关于基本的 view 的知识,不妨看一下View Programming Guide for iOS


Supported File Formats

支持的文件格式

In addition to HTML content, UIWebView objects can be used to display other content types, such as Keynote, PDF, and Pages documents. For the best rendering of plain and rich text in your app, however, you should use UITextView instead.

除了 HTML 内容之外,UIWebView 对象还可以被用来展示其他格式的内容,比如,Keynote,PDF,Pages文件等。为了能够保证文本(plain and rich text)渲染的最佳效果,建议使用 UITextView

State Preservation

状态保存

In iOS 6 and later, if you assign a value to this view’s restorationIdentifier property, it attempts to preserve its URL history, the scaling and scrolling positions for each page, and information about which page is currently being viewed. During restoration, the view restores these values so that the web content appears just as it did before. For more information about how state preservation and restoration works, see App Programming Guide for iOS.

在iOS 6及以后版本的系统中,如果你给 web view 的 restorationIdentifier 属性赋一个值,它将会为每一页保存它的 URL 历史,缩放比例和滚动位置,以及当前正在查看的网页信息。在恢复( restoration)过程中,那个 view 会复原( restore)这些值,因此那个网页(web content)看起来就像它之前的样子一样。如果你想了解更多关于状态保存和恢复是如何运作的信息,不妨读一读 App Programming Guide for iOS

For more information about appearance and behavior configuration, see Web Views.

更多关于外观和行为配置的信息,请看 Web Views

Subclassing Notes

关于继承

The UIWebView class should not be subclassed.

UIWebView 不应该被继承。


Symbols

Setting the Delegate

设置代理

var delegate: UIWebViewDelegate?
The receiver’s delegate.

1
@property(nonatomic, assign) id< UIWebViewDelegate > delegate

The delegate is sent messages when content is loading. See UIWebViewDelegate for the optional methods this delegate may implement.

Important
Before releasing an instance of UIWebView for which you have set a delegate, you must first set its delegate property to nil. This can be done, for example, in your dealloc method.

重要:
在释放一个你已经为其设过 delegate 的 UIWebView 实例之前,你首先一定要将该 UIWebView 对象的 delegate 属性设为 nil。比如说,你可以在你的 dealloc 方法中这样做。

Loading Content

加载内容

1
2
3
4
5
6
7
func load(Data, mimeType: String, textEncodingName: String, baseURL: URL)
Sets the main page contents, MIME type, content encoding, and base URL.
- (void)loadData:(NSData *)data
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)encodingName
baseURL:(NSURL *)baseURL;

1
2
3
4
5
func loadHTMLString(String, baseURL: URL?)
Sets the main page content and base URL.
- (void)loadHTMLString:(NSString *)string
baseURL:(NSURL *)baseURL;
1
2
3
4
func loadRequest(URLRequest)
Connects to a given URL by initiating an asynchronous client request.
- (void)loadRequest:(NSURLRequest *)request;
1
2
3
4
var request: URLRequest?
The URL request identifying the location of the content to load.
@property(nonatomic, readonly, strong) NSURLRequest *request;
1
2
3
4
var isLoading: Bool
A Boolean value indicating whether the receiver is done loading content.
@property(nonatomic, readonly, getter=isLoading) BOOL loading;
1
2
3
4
func stopLoading()
Stops the loading of any web content managed by the receiver.
- (void)stopLoading;
1
2
3
4
func reload()
Reloads the current page.
- (void)reload;
Moving Back and Forward

后退前进

1
2
3
4
var canGoBack: Bool
A Boolean value indicating whether the receiver can move backward.
@property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack;

1
2
3
4
var canGoForward: Bool
A Boolean value indicating whether the receiver can move forward.
@property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
1
2
3
4
func goBack()
Loads the previous location in the back-forward list.
- (void)goBack;
1
2
3
4
func goForward()
Loads the next location in the back-forward list.
- (void)goForward;
Setting Web Content Properties

内容相关属性的设置

1
2
3
4
var allowsLinkPreview: Bool
A Boolean value that determines whether pressing on a link displays a preview of the destination for the link.
@property(nonatomic) BOOL allowsLinkPreview;
1
2
3
4
var scalesPageToFit: Bool
A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.
@property(nonatomic) BOOL scalesPageToFit;
1
2
3
4
var scrollView: UIScrollView
The scroll view associated with the web view.
@property(nonatomic, readonly, strong) UIScrollView *scrollView;
1
2
3
4
var suppressesIncrementalRendering: Bool
A Boolean value indicating whether the web view suppresses content rendering until it is fully loaded into memory.
@property(nonatomic) BOOL suppressesIncrementalRendering;
1
2
3
4
var keyboardDisplayRequiresUserAction: Bool
A Boolean value indicating whether web content can programmatically display the keyboard.
@property(nonatomic) BOOL keyboardDisplayRequiresUserAction;
1
2
3
4
var dataDetectorTypes: UIDataDetectorTypes
The types of data converted to clickable URLs in the web view’s content.
@property(nonatomic) UIDataDetectorTypes dataDetectorTypes;
Running JavaScript
1
2
3
4
func stringByEvaluatingJavaScript(from: String)
Returns the result of running a JavaScript script. Although this method is not deprecated, best practice is to use the evaluateJavaScript(_:completionHandler:) method of the WKWebView class instead.
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
Managing Media Playback

多媒体播放

1
2
3
4
var allowsInlineMediaPlayback: Bool
A Boolean value that determines whether HTML5 videos play inline or use the native full-screen controller.
@property(nonatomic) BOOL allowsInlineMediaPlayback;

1
2
3
4
var mediaPlaybackRequiresUserAction: Bool
A Boolean value that determines whether HTML5 videos can play automatically or require the user to start playing them.
@property(nonatomic) BOOL mediaPlaybackRequiresUserAction;
1
2
3
4
var mediaPlaybackAllowsAirPlay: Bool
A Boolean value that determines whether Air Play is allowed from this view.
@property(nonatomic) BOOL mediaPlaybackAllowsAirPlay;
1
2
3
4
var allowsPictureInPictureMediaPlayback: Bool
A Boolean value that determines whether Picture in Picture playback is allowed from this view.
@property(nonatomic) BOOL allowsPictureInPictureMediaPlayback;
Managing Pages

页面设置

1
2
3
4
var gapBetweenPages: CGFloat
The size of the gap, in points, between pages.
@property(nonatomic) CGFloat gapBetweenPages;

1
2
3
4
var pageCount: Int
The number of pages produced by the layout of the web view.
@property(nonatomic, readonly) NSUInteger pageCount;
1
2
3
4
var pageLength: CGFloat
The size of each page, in points, in the direction that the pages flow.
@property(nonatomic) CGFloat pageLength;
1
2
3
4
var paginationBreakingMode: UIWebPaginationBreakingMode
The manner in which column- or page-breaking occurs.
@property(nonatomic) UIWebPaginationBreakingMode paginationBreakingMode;
1
2
3
4
var paginationMode: UIWebPaginationMode
The layout of content in the web view.
@property(nonatomic) UIWebPaginationMode paginationMode;
最后附上 UIWebView.h

作为一枚成长中的菜鸟,分享和开源精神,还是值得具备的。
如果…
我是说如果,可以关注下 GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
//
// UIWebView.h
// UIKit
//
// Copyright (c) 2007-2015 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIView.h>
#import <UIKit/UIKitDefines.h>
#import <UIKit/UIDataDetectors.h>
#import <UIKit/UIScrollView.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, UIWebViewNavigationType) {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
} __TVOS_PROHIBITED;
typedef NS_ENUM(NSInteger, UIWebPaginationMode) {
UIWebPaginationModeUnpaginated,
UIWebPaginationModeLeftToRight,
UIWebPaginationModeTopToBottom,
UIWebPaginationModeBottomToTop,
UIWebPaginationModeRightToLeft
} __TVOS_PROHIBITED;
typedef NS_ENUM(NSInteger, UIWebPaginationBreakingMode) {
UIWebPaginationBreakingModePage,
UIWebPaginationBreakingModeColumn
} __TVOS_PROHIBITED;
@class UIWebViewInternal;
@protocol UIWebViewDelegate;
NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UIWebView : UIView <NSCoding, UIScrollViewDelegate>
@property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;
@property (nonatomic, readonly, strong) UIScrollView *scrollView NS_AVAILABLE_IOS(5_0);
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
@property (nullable, nonatomic, readonly, strong) NSURLRequest *request;
// 重新加载(刷新)
- (void)reload;
// 停止加载
- (void)stopLoading;
// 回退
- (void)goBack;
// 前进
- (void)goForward;
// 是否能回退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
// 是否能前进
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
// 是否正在加载中
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
// 在OC中调用JavaScript代码
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
// 是否伸缩内容至适应屏幕当前尺寸
@property (nonatomic) BOOL scalesPageToFit;
@property (nonatomic) BOOL detectsPhoneNumbers NS_DEPRECATED_IOS(2_0, 3_0);
// 需要进行检测的数据类型
@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);
@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0); // iPhone Safari defaults to NO. iPad Safari defaults to YES
@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0); // iPhone and iPad Safari both default to YES
@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0); // iPhone and iPad Safari both default to YES
@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0); // iPhone and iPad Safari both default to NO
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0); // default is YES
@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);
@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);
@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback NS_AVAILABLE_IOS(9_0);
@property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE_IOS(9_0); // default is NO
@end
__TVOS_PROHIBITED @protocol UIWebViewDelegate <NSObject>
@optional
// UIWebView在发送请求之前,都会调用这个方法,如果返回NO,代表停止加载请求,返回YES,代表允许加载请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
// 开始发送请求(加载数据)时调用这个方法
- (void)webViewDidStartLoad:(UIWebView *)webView;
// 请求完毕(加载数据完毕)时调用这个方法
- (void)webViewDidFinishLoad:(UIWebView *)webView;
// 请求错误时调用这个方法
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
@end
NS_ASSUME_NONNULL_END


期待


  • 如果在阅读过程中遇到 error || new ideas,希望你能 messages 我,我会及时改正谢谢。
  • 点击右上角的 喜欢 和 订阅Rss 按钮,可以收藏本仓库,并在 Demo 更新时收到邮件通知。
❄︎ 本文结束    感谢简阅 ^_^. ❄︎

本文标题:iOS UIWebViewApple译文

文章作者:寄己的路

原始链接:https://sunyonghui.github.io/AppleTranslation/UIWebViewApple.html

版权声明: 署名-非商业性使用-禁止演绎 4.0 国际 本博客所有文章除特别声明外均为原创,转载务必请「注明出处链接(可点击) - 作者」,并通过E-mail等方式告知,谢谢合作!