UIWebView
一、概览(Overview)
1.支持的文件格式(Supported File Formats)
2.状态保存(State Preservation)
3.关于继承(Subclassing Notes)
二、职能(Tasks)
1.设置代理(Setting the Delegate)
- delegate
2.加载内容(Loading Content)
- - loadData:MIMEType:textEncodingName:baseURL:
- - loadHTMLString:baseURL:
- - loadRequest:
- request
- loading
- - stopLoading
- - reload
3.后退前进(Moving Back and Forward)
- canGoBack
- canGoForward
- - goBack
- - goForward
4.内容相关属性的设置(Setting Web Content Properties)
- allowsLinkPreview
- scalesPageToFit
- scrollView
- suppressesIncrementalRendering
- keyboardDisplayRequiresUserAction
- dataDetectorTypes
5.调用 JavaScript(Running JavaScript)
- - stringByEvaluatingJavaScriptFromString:
6.多媒体播放(Managing Media Playback)
- allowsInlineMediaPlayback
- mediaPlaybackRequiresUserAction
- mediaPlaybackAllowsAirPlay
- allowsPictureInPictureMediaPlayback
7.页面设置(Managing Pages)
- gapBetweenPages
- pageCount
- pageLength
- paginationBreakingMode
- paginationMode
8.废弃的属性(Deprecated Properties)
- detectsPhoneNumbers
三、数据类型(Data Types)
- UIWebViewNavigationType
四、常量(Constants)
- UIWebPaginationBreakingMode
- UIWebPaginationMode
五、文档修订记录(Document Revision History)
UIWebView 参考文档( UIWebView Class Reference )
继承链:UIView : UIResponder : NSObject
遵守协议:
NSCoding,NSObject,UIAppearance,UIAppearanceContainer,UICoordinateSpace,UIDynamicItem,UIFocusEnvironment,UIScrollViewDelegate,UITraitEnvironment
框架导入:@import UIKit;
适用范围:iOS 2.0 and later
相关文档:UIKit User Interface Catalog, Text Programming Guide for iOS
你可以用 UIWebView 来将网页(web content)嵌入到你的 app 中。怎么实现呢?首先创建一个 UIWebView 对象,添加到一个 window 上, 然后给它发送一个请求去加载网页(web content)。你还可以用这个类在网页浏览记录中后退前进(move back and forward),甚至可以设置一些网页属性(web content properties)。
说明:在只支持iOS 8及以后的系统的 app 中,建议使用 WKWebView,而不是 UIWebView 。值得注意的一点是,如果你要渲染的文件不支持运行 JavaScript 的话,不妨将 WKPreferences 的 javaScriptEnabled 属性设为 NO。
我们可以使用 loadHTMLString:baseURL: 方法来加载本地 HTML 文件或者用 loadRequest: 方法来加载网页(web content)。我们还可以通过调用 stopLoading 方法来停止加载,以及通过获取属性 loading 的值来判断一个 web view 是否还处于正在加载的过程中。
如果你想让用户在浏览网页时可以前进后退,你可以通过 button 的 action 对 goBack 和 goForward 方法的调用来控制。当用户不能在某一个方向“移动”时,需要使用 canGoBack 和 canGoForward 属性来禁用按钮的前进后退操作。
默认情况下,一个 web view 会自动将网页中的电话号码转成一个号码链接(Phone links)。当用户在点击那个链接(Phone links)时,系统会自动启动 Phone app 并拨打那个电话号码。你可以将属性dataDetectorTypes 的值设置为一个 UIDataDetectorTypes 位字段来关闭这个电话号码识别行为,因为UIDataDetectorTypes不包括 UIDataDetectorTypePhoneNumber 这个标志位。
你可以通过设置 scalesPageToFit 属性来设置网页(web content)第一次展示在一个 web view 中的页面比例。但仅仅这个属性只在首次展示时有效,首次展示之后用户仍然可以通过手势改变页面比例。
如果你想追踪网页内容(web content)的加载,你需要将 web view 的 delegate 属性赋给一个遵守 UIWebViewDelegate 协议的对象。
重要:不要将 UIWebView 或 UITableView 对象嵌入到 UIScrollView 对象中。如果你这么做了,将会导致一些意想不到的结果,因为那两个嵌套的 view 的 touch 事件会被混淆并且会被错误地处理。
借助 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 。
一、概览(Overview)
1.支持的文件格式(Supported File Formats)
除了 HTML 内容之外,UIWebView 对象还可以被用来展示其他格式的内容,比如,Keynote,PDF,Pages文件等。为了能够保证文本(plain and rich text)渲染的最佳效果,建议使用 UITextView。
2.状态保存(State Preservation)
在iOS 6及以后版本的系统中,如果你给 web view 的 restorationIdentifier 属性赋一个值,它将会为每一页保存它的 URL 历史,缩放比例和滚动位置,以及当前正在查看的网页信息。在恢复( restoration)过程中,那个 view 会复原( restore)这些值,因此那个网页(web content)看起来就像它之前的样子一样。如果你想了解更多关于状态保存和恢复是如何运作的信息,不妨读一读 App Programming Guide for iOS。
更多关于外观和行为配置的信息,请看 Web Views。
3.关于继承(Subclassing Notes)
UIWebView 不应该被继承。(The UIWebView class should not be subclassed. )
二、职能(Tasks)
1.设置代理(Setting the Delegate)
delegate Property
The receiver’s delegate.
Declaration
@property(nonatomic, assign) id< UIWebViewDelegate > delegate
Discussion
The delegate is sent messages when content is loading. See UIWebViewDelegate Protocol Reference for the optional methods this delegate may implement.
重要
在释放一个你已经为其设过 delegate 的 UIWebView 实例之前,你首先一定要将该 UIWebView 对象的 delegate 属性设为 nil。比如说,你可以在你的 dealloc 方法中这样做。
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.
Availability
Available in iOS 2.0 and later.
2.加载内容(Loading Content)
- loadData:MIMEType:textEncodingName:baseURL:
Sets the main page contents, MIME type, content encoding, and base URL.
Declaration
- (void)loadData:(NSData *)data
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)encodingName
baseURL:(NSURL *)baseURL
Parameters
参数 | 含义 |
---|---|
data | The content for the main page. |
MIMEType | The MIME type of the content. |
encodingName | The IANA encoding name as in utf-8 or utf-16. |
baseURL | The base URL for the content. |
Availability
Available in iOS 2.0 and later.
See Also
- loadHTMLString:baseURL:
- loadHTMLString:baseURL:
Sets the main page content and base URL.
Declaration
- (void)loadHTMLString:(NSString *)string
baseURL:(NSURL *)baseURL
Parameters
参数 | 含义 |
---|---|
string | The content for the main page. |
baseURL | The base URL for the content. |
Discussion
To help you avoid being vulnerable to security attacks, be sure to use this method to load local HTML files; don’t use loadRequest:.
Availability
Available in iOS 2.0 and later.
See Also
- loadData:MIMEType:textEncodingName:baseURL:
- loadRequest:
Connects to a given URL by initiating an asynchronous client request.
Declaration
- (void)loadRequest:(NSURLRequest *)request
Parameters
参数 | 含义 |
---|---|
request | A URL request identifying the location of the content to load. |
Discussion
Don’t use this method to load local HTML files; instead, use loadHTMLString:baseURL:. To stop this load, use the stopLoading method. To see whether the receiver is done loading the content, use the loading property.
Availability
Available in iOS 2.0 and later.
See Also
request
- stopLoading
loading
- reload
request Property
The URL request identifying the location of the content to load. (read-only)
Declaration
@property(nonatomic, readonly, strong) NSURLRequest *request
Availability
Available in iOS 2.0 and later.
See Also
- loadRequest:
- stopLoading
loading
- reload
loading Property
A Boolean value indicating whether the receiver is done loading content. (read-only)
Declaration
@property(nonatomic, readonly, getter=isLoading) BOOL loading
Discussion
If YES, the receiver is still loading content; otherwise, NO.
Availability
Available in iOS 2.0 and later.
See Also
request
- stopLoading
- loadRequest:
- reload
- stopLoading
Stops the loading of any web content managed by the receiver.
Declaration
- (void)stopLoading
Discussion
Stops any content in the process of being loaded by the main frame or any of its children frames. Does nothing if no content is being loaded.
Availability
Available in iOS 2.0 and later.
See Also
request
loading
– loadRequest:
– reload
- reload
Reloads the current page.
Declaration
- (void)reload
Availability
Available in iOS 2.0 and later.
See Also
request
loading
– loadRequest:
– stopLoading
3.后退前进(Moving Back and Forward)
canGoBack Property
A Boolean value indicating whether the receiver can move backward. (read-only)
Declaration
@property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack
Discussion
If YES, able to move backward; otherwise, NO.
Availability
Available in iOS 2.0 and later.
See Also
canGoForward
canGoForward Property
A Boolean value indicating whether the receiver can move forward. (read-only)
Declaration
@property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward
Discussion
If YES, able to move forward; otherwise, NO.
Availability
Available in iOS 2.0 and later.
See Also
canGoBack
- goBack
Loads the previous location in the back-forward list.
Declaration
- (void)goBack
Availability
Available in iOS 2.0 and later.
See Also
– goForward
- goForward
Loads the next location in the back-forward list.
Declaration
- (void)goForward
Availability
Available in iOS 2.0 and later.
See Also
– goBack
4.内容相关属性的设置(Setting Web Content Properties)
allowsLinkPreview Property
A Boolean value that determines whether pressing on a link displays a preview of the destination for the link.
Declaration
@property(nonatomic) BOOL allowsLinkPreview
Discussion
This property is available on devices that support 3D Touch. Default value is NO.
If you set this value to YES for a web view, users (with devices that support 3D Touch) can preview link destinations, and can preview detected data such as addresses, by pressing on links. Such previews are known to users as peeks. If a user presses deeper, the preview navigates (or pops, in user terminology) to the destination. Because pop navigation switches the user from your app to Safari, it is opt-in, by way of this property, rather default behavior for this class.
If you want to support link preview but also want to keep users within your app, you can switch from using the UIWebView class to the SFSafariViewController class. If you are using a web view as an in-app browser, making this change is best practice. The Safari view controller class automatically supports link previews.
Availability
Available in iOS 9.0 and later.
scalesPageToFit Property
A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.
Declaration
@property(nonatomic) BOOL scalesPageToFit
Discussion
If YES, the webpage is scaled to fit and the user can zoom in and zoom out. If NO, user zooming is disabled. The default value is NO.
Availability
Available in iOS 2.0 and later.
scrollView Property
The scroll view associated with the web view. (read-only)
Declaration
@property(nonatomic, readonly, strong) UIScrollView *scrollView
Discussion
Your app can access the scroll view if it wants to customize the scrolling behavior of the web view.
Availability
Available in iOS 5.0 and later.
suppressesIncrementalRendering Property
A Boolean value indicating whether the web view suppresses content rendering until it is fully loaded into memory.
Declaration
@property(nonatomic) BOOL suppressesIncrementalRendering
Discussion
When set to YES, the web view does not attempt to render incoming content as it arrives. Instead, the view’s current contents remain in place until all of the new content has been received, at which point the new content is rendered. This property does not affect the rendering of content retrieved after a frame finishes loading.
The value of this property is NO by default.
Availability
Available in iOS 6.0 and later.
keyboardDisplayRequiresUserAction Property
A Boolean value indicating whether web content can programmatically display the keyboard.
Declaration
@property(nonatomic) BOOL keyboardDisplayRequiresUserAction
Discussion
When this property is set to YES, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to NO, a focus event on an element causes the input view to be displayed and associated with that element automatically.
The default value for this property is YES.
Availability
Available in iOS 6.0 and later.
dataDetectorTypes Property
The types of data converted to clickable URLs in the web view’s content.
Declaration
@property(nonatomic) UIDataDetectorTypes dataDetectorTypes
Discussion
Use this property to specify the types of data (phone numbers, HTTP links, email address, and so on) that should be automatically converted to clickable URLs in the web view. When clicked, the web view opens the app responsible for handling the URL type and passes it the URL.
See the UIDataDetectorTypes enumeration for the types of data available for automatic detection.
Availability
Available in iOS 3.0 and later.
5.调用 JavaScript(Running JavaScript)
- stringByEvaluatingJavaScriptFromString:
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.
Declaration
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
Parameters
参数 | 含义 |
---|---|
script | The JavaScript script to run. |
Return Value
The result of running the JavaScript script passed in the script parameter, or nil if the script fails.
Discussion
New apps should instead use the evaluateJavaScript:completionHandler:
method from the WKWebView class. Legacy apps should adopt that method if possible.
IMPORTANT
The stringByEvaluatingJavaScriptFromString: method waits synchronously for JavaScript evaluation to complete. If you load web content whose JavaScript code you have not vetted, invoking this method could hang your app. Best practice is to adopt the WKWebView class and use its evaluateJavaScript:completionHandler: method instead.
Availability
Available in iOS 2.0 and later.
6.多媒体播放(Managing Media Playback)
allowsInlineMediaPlayback Property
A Boolean value that determines whether HTML5 videos play inline or use the native full-screen controller.
Declaration
@property(nonatomic) BOOL allowsInlineMediaPlayback
Discussion
The default value on iPhone is NO.
In order for video to play inline, not only does this property need to be set on the view, but the video element in the HTML document must also include the webkit-playsinline attribute.
Availability
Available in iOS 4.0 and later.
mediaPlaybackRequiresUserAction Property
A Boolean value that determines whether HTML5 videos can play automatically or require the user to start playing them.
Declaration
@property(nonatomic) BOOL mediaPlaybackRequiresUserAction
Discussion
The default value on both iPad and iPhone is YES . To make media play automatically when loaded, set this property to NO and ensure the
Availability
Available in iOS 4.0 and later.
mediaPlaybackAllowsAirPlay Property
A Boolean value that determines whether Air Play is allowed from this view.
Declaration
@property(nonatomic) BOOL mediaPlaybackAllowsAirPlay
Discussion
The default value on both iPad and iPhone is YES.
Availability
Available in iOS 5.0 and later.
allowsPictureInPictureMediaPlayback Property
A Boolean value that determines whether Picture in Picture playback is allowed from this view.
Declaration
@property(nonatomic) BOOL allowsPictureInPictureMediaPlayback
Discussion
The default value is YES on devices that support Picture in Picture (PiP) mode and NO on all other devices.
Availability
Available in iOS 9.0 and later.
7.页面设置(Managing Pages)
gapBetweenPages Property
The size of the gap, in points, between pages.
Declaration
@property(nonatomic) CGFloat gapBetweenPages
Discussion
The default value is 0.
Availability
Available in iOS 7.0 and later.
pageCount Property
The number of pages produced by the layout of the web view. (read-only)
Declaration
@property(nonatomic, readonly) NSUInteger pageCount
Availability
Available in iOS 7.0 and later.
pageLength Property
The size of each page, in points, in the direction that the pages flow.
Declaration
@property(nonatomic) CGFloat pageLength
Discussion
When paginationMode is right to left or left to right, this property represents the width of each page. When paginationMode is top to bottom or bottom to top, this property represents the height of each page.
The default value is 0, which means the layout uses the size of the viewport to determine the dimensions of the page. Adjusting the value of this property causes a relayout.
Availability
Available in iOS 7.0 and later.
paginationBreakingMode Property
The manner in which column- or page-breaking occurs.
Declaration
@property(nonatomic) UIWebPaginationBreakingMode paginationBreakingMode
Discussion
This property determines whether certain CSS properties regarding column- and page-breaking are honored or ignored. When this property is set to UIWebPaginationBreakingModeColumn
, the content respects the CSS properties related to column-breaking in place of page-breaking.
See UIWebPaginationBreakingMode for possible values. The default value isUIWebPaginationBreakingModePage.
Availability
Available in iOS 7.0 and later.
paginationMode Property
The layout of content in the web view.
Declaration
@property(nonatomic) UIWebPaginationMode paginationMode
Discussion
This property determines whether content in the web view is broken up into pages that fill the view one screen at a time, or shown as one long scrolling view. If set to a paginated form, this property toggles a paginated layout on the content, causing the web view to use the values of pageLength and gapBetweenPages
to relayout its content.
See UIWebPaginationMode for possible values. The default value is UIWebPaginationModeUnpaginated.
Availability
Available in iOS 7.0 and later.
8.废弃的属性(Deprecated Properties)
detectsPhoneNumbers (iOS 3.0) Property
三、数据类型(Data Types)
UIWebViewNavigationType
Constant indicating the user’s action.
Declaration
enum { UIWebViewNavigationTypeLinkClicked, // User tapped a link. Available in iOS 2.0 and later.
UIWebViewNavigationTypeFormSubmitted, // User submitted a form. Available in iOS 2.0 and later.
UIWebViewNavigationTypeBackForward, // User tapped the back or forward button. Available in iOS 2.0 and later.
UIWebViewNavigationTypeReload, // User tapped the reload button. Available in iOS 2.0 and later.
UIWebViewNavigationTypeFormResubmitted, // User resubmitted a form. Available in iOS 2.0 and later.
UIWebViewNavigationTypeOther // Some other action occurred. Available in iOS 2.0 and later.
};
typedef NSUInteger UIWebViewNavigationType;
Import Statement
@import UIKit;
Availability
Available in iOS 2.0 and later.
四、常量(Constants)
UIWebPaginationBreakingMode
The manner in which column- or page-breaking occurs.
Declaration
typedef NS_ENUM (NSInteger, UIWebPaginationBreakingMode ) {
UIWebPaginationBreakingModePage, // Content respects CSS properties related to page-breaking. Available in iOS 7.0 and later.
UIWebPaginationBreakingModeColumn // Content respects CSS properties related to column-breaking. Available in iOS 7.0 and later.
};
Import Statement
@import UIKit;
Availability
Available in iOS 7.0 and later.
UIWebPaginationMode
The layout of content in the web view, which determines the direction that the pages flow.
Declaration
typedef NS_ENUM (NSInteger, UIWebPaginationMode ) {
UIWebPaginationModeUnpaginated, // Content appears as one long scrolling view with no distinct pages. Available in iOS 7.0 and later.
UIWebPaginationModeLeftToRight, // Content is broken up into pages that flow from left to right. Available in iOS 7.0 and later.
UIWebPaginationModeTopToBottom, // Content is broken up into pages that flow from top to bottom. Available in iOS 7.0 and later.
UIWebPaginationModeBottomToTop, // Content is broken up into pages that flow from bottom to top. Available in iOS 7.0 and later.
UIWebPaginationModeRightToLeft // Content is broken up into pages that flow from right to left. Available in iOS 7.0 and later.
};
五、文档修订记录(Document Revision History)
下表中列出了文档 *UIWebView Class Reference * 的变化。
日期 | 说明 |
---|---|
2016-03-01 | 着重强调了推荐使用 text view 来展示文本,而非 web view。 |
2015-12-08 | 改进了stringByEvaluatingJavaScriptFromString: 方法的描述,其中包括推荐使用 WKWebView 的 stringByEvaluatingJavaScriptFromString: 方法的建议。 |
2015-09-16 | ① 针对 iOS 9 ,更新了关于 iPad 的 Picture 特性中的 Picture 的信息。② 针对支持 3D Touch 的 allowsLinkPreview 属性,补充了一条描述。 |
2015-07-31 | 补充了一条关于避免使用 loadRequest 方法来加载本地的 HTML 文件的建议。 |
2013-12-16 | ① 为 mediaPlaybackRequiresUserAction 属性添加了一条关于如何让 HTML5 中的音频、视频自动播放的描述. ② 删除了stringByEvaluatingJavaScriptFromString:方法中关于执行 JavaScript 的10秒限制的不准确描述。 |
2013-09-18 | 针对 iOS 7 的更新。 |
2013-04-23 | Added information in the introduction about inspecting web content inside web views.在文档《在 web view 中审查网页元素》的介绍中补充了一些信息。 |
2012-09-19 | 补充了一些在 iOS 6 中引入的方法。 |
2011-10-12 | 针对 iOS 5 的更新。 |
2010-11-15 | 在“不要在 scroll view 中嵌入 UIWebView ”的警告中补充了 UITableView。 |
2010-08-03 | 添加了关于在 scroll view 中嵌入 UIWebView 的警告。 |
2010-06-14 | 描述了在iOS 4.0 中引入的 allowsInlineMediaPlayback 属性和mediaPlaybackRequiresUserAction 属性。 |
2009-06-04 | 修复了破损链接。纠正了 JavaScript 执行时间的错误描述。 |
2009-03-11 | 针对 iOS3.0 的更新。 |
2008-10-15 | Added important release information to delegate.添加了关于释放 delegate 的重要信息。 |
2008-09-09 | 删除了关于缩放比例改变时 delegate 会收到通知的说明。 |
2008-05-30 | New document that describes the class for embedding web content in an application.描述用来在应用中嵌入网页的类的新文档。 |
英文版
Date | Notes |
---|---|
2016-03-01 | Emphasized the recommendation to display text in a text view, instead of in a web view. |
2015-12-08 | Improved the description for the stringByEvaluatingJavaScriptFromString: method, including advice to use the evaluateJavaScript:completionHandler: method of the WKWebView class instead. |
2015-09-16 | ① Updated for iOS 9 with information about the Picture in Picture feature for iPad. ② Added a description for the allowsLinkPreview property, which supports 3D Touch. |
2015-07-31 | Added recommendation to avoid using loadRequest to display a local HTML file. |
2013-12-16 | ① Added description of how to make auto play content work to mediaPlaybackRequiresUserAction. See mediaPlaybackRequiresUserAction. ② Also removed inaccurate description of 10 second limitation for JavaScript execution from stringByEvaluatingJavaScriptFromString:. |
2013-09-18 | Updated for iOS 7. |
2013-04-23 | Added information in the introduction about inspecting web content inside web views. |
2012-09-19 | Added new methods introduced in iOS 6. |
2011-10-12 | Updated for iOS 5. |
2010-11-15 | Added UITableView to the warning about embedding UIWebView objects in scrolls views. |
2010-08-03 | Adding warning about embedding web views in scroll views. |
2010-06-14 | Describes the allowsInlineMediaPlayback and mediaPlaybackRequiresUserAction properties introduced in iOS 4.0. |
2009-06-04 | Fixed broken link. Corrected description of JavaScript execution time. |
2009-03-11 | Updated for iOS 3.0. |
2008-10-15 | Added important release information to delegate. |
2008-09-09 | Removed text about delegate being informed of scale changes. |
2008-05-30 | New document that describes the class for embedding web content in an application. |
参考(Reference): https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/