如何为UIWebView添加缩小动画效果?

14

我正在尝试在键盘出现时平滑缩小一个 Webview,但是动画有问题。一旦动画创建,Webview 的内容就会缩小到其新框架。动画延迟后,Webview 本身可以正确动画到其新大小。

下面的截图展示了它的样子。我将 Webview 的滚动视图背景设置为黄色,视图控制器视图的背景设置为绿色。

1234

如何使内容随着 webView 平滑地动画?这是我用于动画的代码。

-(void)shrinkWebView {
    __weak CDVPlugin* weakSelf = self;
    CGRect frame = weakSelf.webView.frame;
    frame.size.height -= 400;
    [UIView animateWithDuration:2.0
                          delay:3.0
                        options:0
                     animations:^{
                         weakSelf.webView.frame = frame;
                     }
                     completion:nil];
}

感谢您的帮助

这是我正在使用的 Cordova 示例应用的简化版本。

* {
    -webkit-tap-highlight-color: rgba(0,0,0,0); /* make transparent link selection, adjust last value opacity 0 to 1.0 */
}

body {
    -webkit-touch-callout: none;                /* prevent callout to copy image, etc when tap to hold */
    -webkit-text-size-adjust: none;             /* prevent webkit from resizing text to fit */
    -webkit-user-select: none;                  /* prevent copy paste, to allow, change 'none' to 'text' */
    background-color:#E4E4E4;
    background-image:linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-webkit-gradient(
        linear,
        left top,
        left bottom,
        color-stop(0, #A7A7A7),
        color-stop(0.51, #E4E4E4)
    );
    background-attachment:fixed;
    font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
    font-size:12px;
    height:100%;
    margin:0px;
    padding:0px;
    text-transform:uppercase;
    width:100%;
}

/* Portrait layout (default) */
.app {
    background:url(../img/logo.png) no-repeat center top; /* 170px x 200px */
    position:absolute;             /* position in the center of the screen */
    left:50%;
    top:50%;
    height:50px;                   /* text area height */
    width:225px;                   /* text area width */
    text-align:center;
    padding:180px 0px 0px 0px;     /* image height is 200px (bottom 20px are overlapped with text) */
    margin:-115px 0px 0px -112px;  /* offset vertical: half of image height and text area height */
                                   /* offset horizontal: half of text area width */
}

/* Landscape layout (with min-width) */
@media screen and (min-aspect-ratio: 1/1) and (min-width:400px) {
    .app {
        background-position:left center;
        padding:75px 0px 75px 170px;  /* padding-top + padding-bottom + text area = image height */
        margin:-90px 0px 0px -198px;  /* offset vertical: half of image height */
                                      /* offset horizontal: half of image width and text area width */
    }
}

h1 {
    font-size:24px;
    font-weight:normal;
    margin:0px;
    overflow:visible;
    padding:0px;
    text-align:center;
}

.event {
    border-radius:4px;
    -webkit-border-radius:4px;
    color:#FFFFFF;
    font-size:12px;
    margin:0px 30px;
    padding:2px 0px;
}

.event.listening {
    background-color:#333333;
    display:block;
}

.event.received {
    background-color:#4B946A;
    display:none;
}

@keyframes fade {
    from { opacity: 1.0; }
    50% { opacity: 0.4; }
    to { opacity: 1.0; }
}
 
@-webkit-keyframes fade {
    from { opacity: 1.0; }
    50% { opacity: 0.4; }
    to { opacity: 1.0; }
}
 
.blink {
    animation:fade 3000ms infinite;
    -webkit-animation:fade 3000ms infinite;
}
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <button onclick="Keyboard.hideFormAccessoryBar(false)">Shrink</button>
            <input type="text" />
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
            </div>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>


1
最好只对scrollView.contentInset属性进行动画处理,而不是整个框架...我不明白为什么需要delay(可以是0.0),您可以使用键盘动画的持续时间作为您的动画持续时间,目前为0.25(但您可以从键盘出现时发布的通知中读取当前值)。 - holex
@holex 我只是使用那些更大的值,以便问题更加明显。我刚刚尝试使用contentInset属性。在7.1上它有类似的问题。内容立即缩小留下空的黑色空间,然后scrollview的contentInset随着动画而缩小。在8.1上根本没有动画。 - Connor
@connor 这个问题有几种解决方案。你是使用自动布局吗?还是使用Storyboard或者全部都是编程实现的? - Firo
@Firo 我相信这是通过编程完成的。我正在使用cordova工作,所以我没有自己实现视图控制器。 - Connor
3个回答

4
通过JavaScript调整document.body.style.height大小怎么样?
- (void)resizeWebView:(UIWebView *)webView toHeight:(CGFloat)height duration:(CGFloat)duration {
    // We will wrap all webView contents with div and animate it's size
    // so webView content will resize independently of webView's frame.
    NSString *javascriptString = [NSString stringWithFormat:@""
            "function animate(elem, style, unit, from, to, time) {\n"
            "    var start = new Date().getTime(),\n"
            "        timer = setInterval(function() {\n"
            "            var step = Math.min(1,(new Date().getTime()-start)/time);\n"
            "            elem.style[style] = (from+step*(to-from))+unit;\n"
            "            if( step == 1) clearInterval(timer);\n"
            "        }, 25);\n"
            "    elem.style[style] = from+unit;\n"
            "}\n"
            "document.body.style.position = 'relative';\n"
            "animate(document.body, 'height', 'px', document.body.offsetHeight, %f, %f)",
        height, duration*1000];
    [webView stringByEvaluatingJavaScriptFromString:javascriptString];

    BOOL isGrowing = height > webView.frame.size.height;

    // If webView is growing, change it's frame imediately, so it's content not clipped during animation
    if (isGrowing) {
        CGRect frame = webView.frame;
        frame.size.height = height;
        webView.frame = frame;
    }

    __weak typeof(webView) weakWebView = webView;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        __strong typeof(weakWebView) webView = weakWebView;
        // If webview was shrinking, change it's frame after animation is complete
        if (!isGrowing) {
            CGRect frame = webView.frame;
            frame.size.height = height;
            webView.frame = frame;
        }
        // Remove remove body position constraints
        [webView stringByEvaluatingJavaScriptFromString:@""
                "document.body.style.position = document.body.style.height = null;"
        ];
    });
}

- (void)toggleButtonTapped:(id)sender {
     [self resizeWebView:self.webView toHeight:300 duration:0.4];
}

示例

编辑:更新代码,现在所有的HTML都用<div style="position:relative;">包装,以便绝对定位的元素也可以进行动画。

编辑2:好吧,操作DOM结构不是一个好主意——如果你试图在用户在webView中输入并出现键盘时调整webView的大小,输入将失去焦点,并且键盘会立即隐藏。所以现在我只需将document.body.style.position = 'relative'添加到代码中并调整body的大小即可。

我还创建了一个UIWebView类别,您可以通过cocoapods安装它。


谢谢你的回答。你能分享更多的代码吗?我正在从按钮按下调用你的函数,但仍然看到跳跃行为。 - Connor
@connor 添加了一些示例代码。如果此函数对您不起作用,则可能是您要调整大小的 HTML 存在问题。也许您需要调整其他节点的大小,而不是 body。您能否将页面的 html+css 粘贴到某个地方? - glyuck
我已经添加了一些HTML/CSS。 - Connor
好的,代码已更新,现在应该可以与您的HTML一起使用了。问题出在您的.app div中的position: absolute;。它的位置只有在窗口大小改变时才会重新计算,并且与body.height(我正在进行动画处理)无关。现在我用<div style="position:relative;">包装所有的HTML并对其高度进行动画处理。因此,所有绝对定位的元素的位置也会被动画处理。 - glyuck
@connor,代码有更新。直接操作页面的 DOM 不是个好主意。另外我创建了一个库,希望能为大家节约时间。欢迎提交问题和拉取请求 :-) - glyuck
显示剩余2条评论

1
这是一段示例代码。
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *webViewBottomConstraint;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Keyboard Notification
-(void)keyBoardShow:(NSNotification*)noti
{

    CGRect keyboardBounds;
    [[noti.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];

    [UIView animateWithDuration:duration.floatValue animations:^{
        [self.webViewBottomConstraint setConstant:keyboardBounds.size.height];
        [self.view layoutIfNeeded];
    }];

}

-(void)keyBoardHide:(NSNotification*)noti
{

    CGRect keyboardBounds;
    [[noti.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    [UIView animateWithDuration:duration.floatValue animations:^{
        [self.webViewBottomConstraint setConstant:0];
        [self.view layoutIfNeeded];
    }];

}

@end

希望它能对你有所帮助。

嗨,史蒂夫。webViewBottomConstraint是什么?谢谢。 - Dmitry Minkovsky

-1

问题出在动画上。Webview 的大小随着键盘的弹出可以正确地进行动画处理,但其内容会立即跳转到新的大小。我无论是否使用键盘通知都能够复现这个问题。 - Connor
哦,我明白了!那么我相信你可能不会喜欢这个答案……根据我的WebViews经验,你无法从iOS端控制太多。HTML会对键盘做出反应,如果你想解决这个问题,你需要使用JS(我看到你可能正在使用JS库来显示内容)来改变元素的位置。我自己也做过这样的事情,但是我没有访问代码的权限 :(. 解决方法是通过JS桥接实现的。 - wolffan
这不是在我的键盘上的问题。我创建了一个基本的测试用例(在屏幕截图中显示),通过按钮单击来触发动画。 - Connor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接