Skip to content

Instantly share code, notes, and snippets.

@asakasinsky
Created April 20, 2015 21:16
Show Gist options
  • Save asakasinsky/8c8dd0b012fb92423e41 to your computer and use it in GitHub Desktop.
Save asakasinsky/8c8dd0b012fb92423e41 to your computer and use it in GitHub Desktop.
[Источник](http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/)
3. __Избегайте изменения между 'display:none;' и 'display: something;'.__ Изменение display-состояния в iOS сродни добавлению или удалению элементов из DOM и приводит к пересчету дерева, длительность которого зависит от количества элементов DOM, что может вполне может привести к "тормозам" UI на секунду или больше. __Как исправить:__ Вместо использования свойства display, используйте свойство transform, и, если будет нужно скрыть элемент, сделайте так "translate(100000px,100000px);", и если захотите его показать, просто установите значения равными нолю: "translate(0px,0px);". И да, нужно будет установить "position: absolute;". Использование этого метода, в сравнении с использованием "display", требует больше работы, однако вырастет производительность вашего веб-приложения.
не-Ретина-размеры ровно в 2 раза меньше Ретина-размеров
то есть 101px Ретина соответствуют 50.5px не-Ретина
==============================================
Элементы, по которым «тапают» не должны быть маленькими (не менее 40x40px)
==============================================
3. Design on a Device
iOS devices have a range of pixel densities and vary in their reproduction of colour. When designing iOS apps, you should take that into account.
In order to get an accurate idea of what your app will look like, you need to render it on a range of devices: Retina and non-Retina, tall and short, iPad and iPhone. Use [LiveView](http://www.teehanlax.com/blog/how-to-design-pixel-perfect-photoshop-files-for-ios-apps/) or Skala to mirror your photoshop files on your device. Lastly, don’t forget to vary the screen brightness to make sure your app looks good in all circumstances.
4. Animate your Interface
Animations are easy on iOS – Apple has gone to a lot of trouble so apps can easily be supplemented with cool animated transitions. It would be a shame not to take full advantage of this opportunity.
Unfortunately, animations are not easily conveyed through PSDs. The best idea for designing awesome animations is to work with a developer to prototype them on an actual device. Together, you can make throwaway apps that explore your idea for an animation. This will let you get a precise feel for exactly how your animations behave.
When designing animations, take advantage of what the user is already familiar with. Users expect that when they tap on an item to see more details, the new view should “push” in from the right; they also expect views for creating new content to slide up from the bottom. Mimic those motions in your own custom animations and don’t associate new actions with the existing animations. You should lean on what the user is familiar with to give them a better sense of familiarity and trust with your app.
5. Involve Developers Early
We believe that the best apps are made when developers are involved early in the design process, and when designers stay involved late in the development process. Collaboration between designers and developers will lead to some great work.
Implementing any reasonably complex design will have implementation challenges – the sooner developers can start thinking about solving those problems, the better the solutions will be.
We developers have ideas about interfaces that we’re not necessarily able to polish into an actual design. We also know iOS like the back of our hands, so we can point out elements of designs that don’t fit well within iOS. When designers and developers work together, awesomeness happens.
So there you go. Apps aren’t websites. Design universally. Design on a device. Animations are awesome. Involve developers early. These points will get you most of the way there – the rest is up to you.
==============================================
this enables native elastic overflow scrolling in iOS
#divToScroll{
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
==============================================
Вся анимация, даже 2D делается через
transform: translate3d(0,0,0);
-webkit-transform: translate3d(0,0,0);
Это самый оптимизированный вариант, так как при его использовании iOS задействует hardware-acceleration
Show or hide elements with 3D transforms when possible
Invariably you will have some elements that need to be shown or hidden based on user interaction. For example, a modal dialog or menu of some sort. The easiest way to do this is usually display:none or visibility:hidden, however, you can achieve a significant speed increase by using a 3D transform to position the element offscreen. In my experience, using this technique to show or hide menus resulted in a 3-5X speed increase over display:none.
==============================================
Tip #4 - Preload images
Even though your images are already stored on the iOS device there will still be a noticeable "pop-in" when the images are first displayed. I found [CSS3 caching](http://www.ajaxera.com/image-preloading-through-css3-caching/) to be the best method for dealing with this issue. If you are not keen on enumerating and maintaining a list of every background image you use in your app, here is a [jQuery plugin](https://gist.github.com/3581792) that will preload any background image referenced in your CSS.
==============================================
Tip #5 - Phark image replacement does not play nice with 3D transforms
Image replacement by setting a large, negative text-indent is great for accessibility since screen readers will find the text and browsers will only display the image. However, the text-indent will make for unbearably choppy 3D transitions in mobile Safari (this is actually related to tip #7). Fortunately, there are alternatives to Phark that perform much better.
==============================================
Tip #6 - Velocity scrolling!
Velocity scrolling is a super easy way to get a native feel in the scrollable portions of your app. It is simple to enable it on any scrollable area with a CSS rule:
-webkit-overflow-scrolling: touch;
That's it! However, be warned, Apple's current implementation is a little bit buggy.
Tip #7 - Respect maximum texture sizes
Each iOS device has a maximum texture size. If you try to smoothly transform an element larger than the maximum texture size, the element will be broken into smaller tiles before the transform is applied, and this a very slow and ugly process.
Tip #8 - Hide large, off-screen images
If your app displays many large images, hide the images that are off-screen. Otherwise, it doesn't take many large images to unceremoniously crash your app. Both display:none and visibility:hidden work just fine, but tip #3 will not cut it here.
Tip #9 - Eliminate tap event delays
It takes mobile Safari about a third of a second (300 milliseconds) to decide that a touch start event followed by a touch end event should be synthesized into a click event. Plenty of frameworks, such as jQuery Mobile, have "tap" handling code that can eliminate this delay for you.
==============================================
remove grey background on link clicked in ios safari
Webkit has a specific style property for that: -webkit-tap-highlight-color.
If you want to remove the highlight completely—
.myButton {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
==============================================
/* styles.css */
.logo {
background: url('images/logo.png') center center no-repeat;
background-size: 320px 100px;
}
That code will render logo.png as 320px wide by 100px tall. It will scale the image to make it fit those dimensions, so unfortunately this trick will not work with sprites, but it will ensure that the image is always rendered within those dimensions.
Now, the magic happens by specifying a different, high-resolution (640px by 200px), background image.
/* highres.css */
.logo {
background-image: url('images/logo_highres.png');
}
The trick is doing so ONLY for retina display, or similarly high-resolution devices. This is where a special webkit media query comes into play:
==============================================
1. Click on the launch arrow in Safari
2. From the drop down menu select “Add to Home Screen”
3. Don’t forget to give your Web App a name
4. Once done your Web App should look like this:
Viewport
Viewport changes the logical size of the viewable area on the iOS device.
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
Here are all the available options:
width – Width of viewport in pixels. [Default: 980, Range: 200 - 10,000]
height – Height of viewport in pixels. [Default: calculated with the width and aspect ratio of the device, Range: 223 - 10,000]
initial-scale – The initial scale of the viewport. [Default: calculated to fit the webpage in the area available, Range: calculated with minimum-scale and maximum-scale properties.]
minimum-scale – The minimum scale of viewport. [Default: 0.25, Range: >0 - 10]
maximum-scale – The maximum scale of viewport. [Default: 1.6, Range: >0 - 10]
user-scalable – Whether the user can zoom in and out. [Default: yes, Options: yes or no]
<meta name="apple-mobile-web-app-capable" content="yes">
Removing the Toolbars and making the Website iOS capable simply removes Safari’s toolbars and makes your site fullscreen.
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
This changes the colour of the iOS’s status bar there are three settings you can use:
1. default
2. black
3. black-translucent
Note: If you use default or black the web page content will appear below the iOS’s status bar, to give your website more real estate it’s recommended using black-translucent as it makes the website appear behind the Status bar.
<meta name="apple-mobile-web-app-title" content="Touch-n-Get">
Application Icon
<link rel="apple-touch-icon" href="img/app-icon.png"/>
The Breakdown
This is what the user will see when they add your app to their home screen (SpringBoard). You can specify three different types of icons depending on what device the user is using.
1. iPod Touch, iPhone and iPad <link rel="apple-touch-icon" href="touch-icon-iphone.png" />
2.
3. iPhone <link rel="apple-touch-icon" sizes="114x114" href="touch-icon-iphone4.png" />
4.
5. iPad <link rel="apple-touch-icon" sizes="72x72" href="touch-icon-ipad.png" />
6.
5. Splash Screen
<link rel="apple-touch-startup-image" href="img/splash-screen.png" />
The Breakdown
This will add a Splash Screen to your Web App. Below are the sizes you’ll need for both iPad and iPhone/iPod Touch, these include the status bar area as well.
• iPad Landscape – 1024 x 748 <link rel="apple-touch-startup-image" sizes="1024x748" href="img/splash-screen-1024x748.png" />
• iPad Portrait – 768 x 1004 <link rel="apple-touch-startup-image" sizes="768x1004" href="img/splash-screen-768x1004.png" />
• iPhone/iPod Touch Portrait – 320 x 480 (standard resolution) <link rel="apple-touch-startup-image" href="img/splash-screen-320x460.png" />
• iPhone/iPod Touch Portrait – 640 x 960 pixels (high-resolution) <link rel="apple-touch-startup-image" sizes="640x960" href="img/splash-screen-640x960.png" />
If creating a Web App for iPad compatibility it’s recommended that both Landscape and Portrait sizes are used.
Однако, по материалам опубликованного ранее на хабре вопроса, у нас возникнут проблемы с валидацией.
Решение
Завершая эксперимент, описанный там же в комментариях пользователем kaluzhanin проверкой на iPhone 4S, подведу итог: можно убрать «rel» из ссылок и положить в корень следующие изображения соответствующего размера:
• iPhone 3GS — apple-touch-icon-57x57.png
• iPhone 3G — apple-touch-icon-57x57.png
• iPhone 4S — apple-touch-icon-114x114.png
• iPad — apple-touch-icon-72x72.png
• iPod Touch 2G — apple-touch-icon-57x57.png
• iPod 4 — apple-touch-icon.png
To learn more about the Web Apps for iOS visit the [Safari Web Content](http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safariwebcontent/configuringwebapplications/configuringwebapplications.html)
documentation page.
==============================================
Номер телефона
По умолчанию в Safari включена функция автоматического определения номеров телефонов на странице. Это влечет за собой «оборачивание» номера как ссылку, со всеми вытекающими. Как следствие — получаем несоответствие макету.
Решение
Прописываем в head:
<meta name = "format-detection" content = "telephone=no" />
==============================================
Общие положения
Прежде, чем начинать устранять проблемы внешнего вида проекта на iOS устройствах, хорошо бы сразу определиться — что будет более рентабельно. Я достаточно часто наблюдал ситуацию, когда сайт обрастает ненужными, лишними конструкциями в угоду приемлемого вида с айфона. А если оригинальная версия сайта еще грешит и флешем…
Иногда гораздо лучше (как с экономической, так и с точки зрения юзабилити) использовать мобильную версию, со своими стилями и скриптами. Определить, с какого устройства к нам пришел пользователь несложно:
JavaScript:
PHP:
Подключать стили без использования JS можно 2 способами:
1. через @media в основном файле стилей
2. указывая в head путь к стилю
Пример первого способа описан ниже, в пункте «Изображения», второй же выглядит так:
<link href="mobile1024.css" rel="stylesheet" type="text/css" media="only screen and (max-device-width: 1024px)" />
Принцип действия в обоих вариантах один — мы используем в качестве идентификатора максимальное разрешения устройства, на котором будет отображаться проект. Можно, кстати, записать то же, только без "only" — это своего рода защита от старых браузеров.
В принципе, можно сразу отсылать пользователя на мобильную версию сайта (пример для iPad):
RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://mobile.your-site.com [R=301]
Однако, как показывает практика, мобильная версия не всегда удобна и, что более важно — не всегда привычна пользователю. Лучше дайте право выбора: к примеру, при первом переходе на сайт страницу с вопросом/предложением использовать мобильную версию.
Изображения:
Веб разработчики, проверяя свой код на жизнеспособность под iOS время изредка сталкиваются с проблемой использования больших изображений в качестве фона. Причем, «больших» следует понимать как объемных по разрешению. Как оказалось, существует искусственное ограничение для Safari под управлением iOS.
Если вкратце, то дело обстоит так:
1. Если на борту яблочного девайса ОЗУ менее 256 Мб, то максимальный размер изображений, который можно использовать безболезненно – 3 мегапикселя (что, фактически, ≤ 3 * 1024 * 1024 = 3 145 728 пикс.)
2. Устройства, значение объема ОЗУ которых больше 256 Мб, корректно отобразят изображения до 5 мегапикселей.
Основной мотивацией данного решения, по версии самой Apple, является невысокая скорость передачи данных в EDGE, 3G и Wi-Fi сетях, однако жесткая привязка к объему памяти явно дает понять, что это не что иное, как попытка избежать «тормозов», которые неизбежно возникнут при декодировании и масштабировании крупных изображений.
Стоит заметить, что данные ограничения актуальны для изображений .GIF, .PNG, и .TIFF формата. Что касается изображений формата JPEG, то можно с чистой совестью использовать изображения до 32 мегапикселей, но только в режиме сабсэмплинга. Напомню, что при сохранении изображения в том же Photoshop, сабсэмплинг автоматически используется для уровня качества «Low» и «Medium». Это, в свою очередь, означает то, что фактически же, максимальное разрешение при кодировании в более-менее приемлемом качестве ограничено теми же 32 / 16 = 2 мегапикселями. Все что выше — автоматически будет обработано вышеуказанным методом.
Решение:
Специально перерезаем наше изображение на уменьшенное, подгружая его одним из вышеописанных способов, например — через @media:
Для экранов с разрешением > 1024 будет отображаться фон, указанный в CSS ранее.
Скрипты:
Скрипты, время выполнения которых превышает 10 секунд, принудительно убиваются — причем, не факт, что это будет лицеприятный этап: в лучшем случае может статься, что пользователь увидит то, что ему видеть не следует, по крайней мере, не нажав пару кнопок.
Решение:
Оптимизация, только оптимизация. И тестируйте ваши скрипты. Причем, именно на тех устройствах, где они должны работать. На случай, если кто-то забыл — приведу код того, как это сделать:
И гораздо лучше, если время выполнения будет максимально отдалено от критических 10 секунд — вы никогда не знаете, что еще висит в фоне и отъедает ресурсы и какая именно версия девайса будет у юзера в руках (соответственно — производительность). Хотя, за скрипты, которые даже близко подходят к этой отметке, следует отрывать руки.
Если тяжеловесной конструкции не избежать — задумайтесь об отдельной версии проекта для мобильных устройств, либо хотя бы об «облегченной» версии скрипта.
==============================================
Fixed Elements and Scrolling Divs in iOS 5
kylejlarson.com
Nov 11th 2011
I’ve been playing around with creating a web app for iOS and testing some of the new features in mobile safari that were released with iOS 5. Fixed divs and the ability to scroll a div are common in iOS native apps but were difficult to implement in a web app. These have both been added in the new safari but they still require some work-arounds to make them function like you probably want.
Fixed Elements
The first versions of iOS didn’t support fixed elements. They would fix correctly to the screen, but then they would scroll along with the rest of your content. In iOS 5, fixed elements (e.g. position: fixed; bottom: 0;) work as expected.
Keep in mind you’ll want to use the iOS meta tags if you’re designing specifically for the device. The first line below prevents the default scaling for sites that aren’t built for to adapt to the screen size and the second allows you to save the site and run it without the browser bars.
<meta name="viewport" content="initial-scale = 1.0, user-scalable = no">
<meta name="apple-mobile-web-app-capable" content="yes" />
The first issue with the fixed elements is that your site will still have the ‘bounce’ effect when scrolling past the top/bottom of your content that reveals the browser chrome (background beneath your page as it bounces). If your site doesn’t need to scroll this is a very simple fix, just add a line to prevent the default action when moving your finger:
<script type="text/javascript">
document.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
</script>
If you want scrolling areas, but don’t want the browser chrome to show then continue on!
Scrolling Divs
Another new feature in iOS 5+ is divs can finally scroll. To make a div scroll you’ll just need to add the following (this example has a fixed header but adjust the positioning to fit your app):
The trick here is adding the -webkit-overflow-scrolling to anywhere you’d normally set your overflow. The downside of Apple’s implementation is that the div doesn’t bounce as you’d hope when you are already at the absolute top or bottom. Instead of bouncing the div being scrolled, it bounces the whole page and reveals the browser chrome. This is where you’ll need a javascript fix.
Fixing the Scrolling Element
Thanks to the development community there are several great options out there that you can implement. These include Scrollability and iScroll. My issue with iScroll was that it doesn’t play well with form elements if you have them in your app. At the time of this article, Scrollability’s author says it isn’t ready for release usage, but it seems to be a great solution if you want to test it. If you want your app to work well with old implementations of iOS you’ll need something similar to this (plus you’ll also need to code around the fixed elements issue), but for now we’re only addressing iOS 5+ and we’ll will save fallbacks for a different article.
The solution I like the best for iOS5 is also the simplest. Joe Lambert’s ScrollFix increases the page slightly when at the top or bottom to make your div bounce instead of the whole browser. It’s very simple to add to an element that you already have scrolling:
<script type="text/javascript" src="scrollfix.js"></script>
<script type="text/javascript">
var scrollingContent = document.getElementById("myScrollingDiv");
new ScrollFix(scrollingContent);
</script>
If you have multiple scrolling divs just apply this again to those divs. For my app I’ve got several divs which either shown or hidden and each has this script applied. We’re almost there, but two possible issues still exist. When scrolling on our fixed elements and our scrolling elements that don’t have enough content to overflow the page, the browser chrome is still revealed.
Preventing Fixed Headers from Showing Browser Chrome
This is a pretty simple fix, similar to what was described above. In my fixed header I’ve got multiple elements, so I made sure that each element or it’s parent had the class “noBounce” and then applied the following script:
This prevents the default bounce when dragging those classed elements, but doesn’t break the div that you want to scroll.
Adapting for Elements That Don’t Overflow
When creating my code some of the divs for my main content overflowed the browser window which triggers the scrollbar and bounce fix, but others didn’t. There are several ways to address this, but the easiest solution I came up with just extends all divs so they have at least a bit of scroll. To do that I added this jQuery script (you could do something similar in straight JS as well) to all my content divs:
<div class="scrollable">
<div class="contentWrapper">
Your content
</div>
</div>
<script type="text/javascript">
$('.contentWrapper').css('min-height', $(window).height() - 55 + 'px');
</script>
You’ll need to adjust the “- 55″ portion based on your application. I have it in there to prevent it from having too much scroll because of my fixed header.
Here’s a really basic demo if you want to test it out in your mobile browser: kylejlarson.com/files/iosdemo/
==============================================
==============================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment