<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[iOS layouts for web developers - Medium]]></title>
        <description><![CDATA[iOS layouts for web developers - Medium]]></description>
        <link>https://medium.com/ios-layouts-for-web-developers?source=rss----3f3469644fa1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>iOS layouts for web developers - Medium</title>
            <link>https://medium.com/ios-layouts-for-web-developers?source=rss----3f3469644fa1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:30:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ios-layouts-for-web-developers" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS layouts for web developers #5 — events handling]]></title>
            <link>https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-5-events-handling-93f45d350a0d?source=rss----3f3469644fa1---4</link>
            <guid isPermaLink="false">https://medium.com/p/93f45d350a0d</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bright Inventions]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 07:00:50 GMT</pubDate>
            <atom:updated>2019-09-01T07:57:28.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Time to finish the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers/"><strong>iOS layouts for web developers</strong> series</a> with the post about events. Earlier in the series you might read about <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-1-basic-building-blocks/">the controls</a>, <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-2-control-positioning/">control positioning</a>, <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-3-managing-appearance/">managing the appearance</a> and <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-4-css-properties-replacements/">CSS properties replacements</a>.</p><h3>Touchy state of the mobile touch events</h3><p>Both in the web and in iOS we employ event-based models to define and control the interactions between our application and the external world, especially the user. The general idea of listening and reacting to particular events on specific parts of the UI or the whole application is the same on both environments. But the set of events is distinct and the main difference we need to always be aware is there are different ways to interact with the classical web than with the mobile device.</p><p>The web’s basic <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings">DOM events model</a> was designed when touch interfaces were still very far from mainstream devices. It assumes the application is controlled by the mouse and the keyboard, thus the events carry the information like where the mouse pointer is or which key was pressed. And now, when we use the web on the mobile device, we’re still constrained to what type of interaction the browser supports and in a lot of cases we still need to talk in terms of clicks and mouse moves instead of gestures.</p><p>The story about <a href="http://www.html5rocks.com/en/mobile/touch/">proper touch events in the web</a> is <a href="http://www.w3.org/Mobile/mobile-web-app-state/#User_interactions">long and convoluted</a>. First, Safari introduced own <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW22">non-standard touch events support</a> back in iOS 2.0. The de-facto standard was adopted by few other mobile browsers and later codified as the <a href="http://www.w3.org/TR/touch-events/">W3C standard</a>, but its adoption is <a href="http://caniuse.com/#feat=touch">still quite poor</a>. Meanwhile the new, more generic alternative concept of <a href="http://www.w3.org/TR/pointerevents/">Pointer Events</a> was coined, specified and <a href="http://caniuse.com/#feat=pointer">introduced in Internet Explorer</a>. This led to the support fragmentation and uncertainty for developers what to rely on and what to expect in the future.</p><p>On the other hand we have native mobile platforms like iOS that know much better how the contemporary device is controlled. Instead of mouse and keyboard events, the mobile platform is concerned about <a href="https://developer.apple.com/library/prerelease/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Introduction/Introduction.html">multitouch gestures like panning or pinching or accelerometer-based motion recognition</a> and exposes it via the high-level gesture API instead of low-level information about each and every touch or finger movement.</p><p>Of course, on a conceptual level, there are some analogies and some of the most common native gestures can be translated quite directly into web world — the example is a scroll gesture, done by tapping the screen and dragging the app’s content — mobile browsers happen to emit scroll events then.</p><h3>Simplified gestures handling</h3><p>Events in iOS are approached at multiple levels of abstraction, giving the developer the way to either easily use the system default gestures or alternatively dive down to more complex but more powerful API.</p><p>The simpler layer available are <a href="https://developer.apple.com/library/prerelease/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html#//apple_ref/doc/uid/TP40009541-CH2-SW2">gesture recognizers</a>. Views can have multiple gesture recognizers attached, each configured to detect a particular, possibly complex gesture like pinching (<a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIPinchGestureRecognizer_Class/index.html#//apple_ref/occ/cl/UIPinchGestureRecognizer">UIPinchGestureRecognizer</a>) or finger rotation (<a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIRotateGestureRecognizer_Class/index.html#//apple_ref/occ/cl/UIRotationGestureRecognizer">UIRotationGestureRecognizer</a>). When the gesture is detected, the recognizer calls its target - the callback we defined when setting the recognizer up:</p><p>- (void)viewDidLoad { [super viewDidLoad]; UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondToDoubleTapGesture:)]; doubleTapRecognizer.numberOfTapsRequired = 2; [self.view addGestureRecognizer:doubleTapRecognizer]; } - (void)respondToDoubleTapGesture:(id)sender { // react on double tap event here }</p><p>There’s no direct analogy available for complex gestures in the web world. Mobile browser apps often have their own handling for such a gestures, not even passing the raw gesture to the web app currently opened. For example, when pinching the website on the mobile device, it is zoomed in or out <a href="http://stackoverflow.com/questions/995914/catch-browsers-zoom-event-in-javascript">without the web app being notified</a> about that event directly. The solution to handle complex gestures in mobile web is to defer to 3rd-party libraries that employ the low-level handling mechanisms to emulate the gesture events. Examples are <a href="http://hammerjs.github.io/">Hammer.js</a> or <a href="https://github.com/hotstudio/touchy">Touchy</a>.</p><blockquote><em>3rd-party libraries to handle complex events ↔ built-in gesture recognizers</em></blockquote><h3>Simple events simplified even more</h3><p>For simpler events that do not require complex “recognizing” of movements pattern and consist just a single interaction, like tap, there is simplified mechanism available in iOS via UIControl’s <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/occ/instm/UIControl/addTarget:action:forControlEvents:">addTarget:action:forControlEvents:</a> method, where we specify callbacks for particular events directly in the control:</p><p>- (void)viewDidLoad { [super viewDidLoad]; UIButton *button = // create or find a button [button addTarget:self action:@selector(respondToTapGesture:) forControlEvents:UIControlEventTouchUpInside]; } - (void)respondToTapGesture:(id)sender { // react on tap event here }</p><p>The web analogy here is pretty clear — it’s like adding an event listener to the DOM element, either directly using <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">element.addEventListener API</a> or through convenient libraries like <a href="http://api.jquery.com/on/">jQuery and its </a><a href="http://api.jquery.com/on/">on function</a> etc.</p><blockquote><em>addEventListener and its wrappers ↔ </em><em>addTarget:action:forControlEvents:</em></blockquote><p>What else we need to know here is the “translation table” from the DOM event to its <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/doc/constant_group/Control_Events">corresponding </a><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/doc/constant_group/Control_Events">UIControlEvent type</a>. Of course the analogies are coarse-grained as always, but here we go:</p><blockquote><em>mousedown event ↔ </em><em>UIControlEventTouchDown</em></blockquote><blockquote><em>mouseup event, conventionally also </em><em>click event ↔ </em><em>UIControlEventTouchUpInside</em></blockquote><blockquote><em>change event on form controls ↔ </em><em>UIControlEventValueChanged</em></blockquote><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_and_drop"><em>drag events</em></a><em> ↔ </em><em>UIControlEventTouchDragInside, </em><em>UIControlEventTouchDragOutside, </em><em>UIControlEventTouchDragEnter, </em><em>UIControlEventTouchDragExit</em></blockquote><h3>Low-level events handling</h3><p>There is also lower level touch event handling available within <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/doc/uid/TP40006783-CH4-SW13">UIResponder base class</a>, which fortunately is a base class for UIView allowing these methods to be used everywhere. There are plenty of methods available to be overriden when our view implementation is interested in being notified about events like beginning of the touch (<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/touchesBegan:withEvent:">touchesBegan:withEvent:</a>), touch move (<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/touchesMoved:withEvent:">touchesMoved:withEvent:</a>) or touch end (<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/touchesEnded:withEvent:">touchesEnded:withEvent:</a>). These events consists of locations for all touch points, allowing multitouch support. But in order to detect any pattern, we need to analyse the data on our own. This resembles what we have <a href="https://developer.mozilla.org/en-US/docs/Web/API/Touch_events">available in some web browsers</a>.</p><blockquote><em>listening on </em><em>touchstart event ↔ overriding </em><em>touchesBegan:withEvent: method</em></blockquote><blockquote><em>listening on </em><em>touchmove event ↔ overriding </em><em>touchesMoved:withEvent: method</em></blockquote><blockquote><em>listening on </em><em>touchend event ↔ overriding </em><em>touchesEnded:withEvent: method</em></blockquote><blockquote><em>listening on </em><em>touchcancel event ↔ overriding </em><em>touchesCancelled:withEvent: method</em></blockquote><p>Raw <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/doc/uid/TP40006783-CH4-SW19">motion events</a> handling is also available within UIResponder in the same fashion as touch events, using <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/motionBegan:withEvent:">motionBegan:withEvent:</a> method and its siblings. In the web we might use <a href="http://mobiforge.com/design-development/html5-mobile-web-device-orientation-events">device motion and orientation events</a> instead.</p><blockquote><em>listening on </em><em>devicemotion event ↔ overriding </em><em>motionBegan:withEvent: and </em><em>motionEnded:withEvent: methods</em></blockquote><h3>Other events</h3><p>For the sake of completeness, I’d mention few more event types that are somehow supported by both the web standard and iOS.</p><blockquote><em>listening on </em><em>window.onload, jQuery </em><em>$(document).ready or similar events ↔ overriding </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/viewDidLoad"><em>UIViewController.viewDidLoad</em></a><em> method</em></blockquote><blockquote><em>listening on </em><em>window.resize event ↔ overriding </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITraitEnvironment_Ref/index.html#//apple_ref/occ/intfm/UITraitEnvironment/traitCollectionDidChange:"><em>traitCollectionDidChange:</em></a><em> method on the view or view controller</em></blockquote><blockquote><em>listening on </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation"><em>deviceorientation</em></a><em> event ↔ adding observer to </em><em>NSNotificationCenter that observes for </em><a href="http://thinkdiff.net/iphones/orientation-detection-at-runtime-in-ipad-or-iphone/"><em>UIDeviceOrientationDidChangeNotification</em></a><em>; alternatively overriding </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITraitEnvironment_Ref/index.html#//apple_ref/occ/intfm/UITraitEnvironment/traitCollectionDidChange:"><em>traitCollectionDidChange:</em></a><em> method on the view or view controller</em></blockquote><blockquote><em>set of proposed solutions for </em><a href="http://www.w3.org/Mobile/mobile-web-app-state/#Sensors_and_hardware_integration"><em>sensors and hardware integration</em></a><em>, not yet implemented ↔ </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/remoteControlReceivedWithEvent:"><em>remote control events on </em></a><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/#//apple_ref/occ/instm/UIResponder/remoteControlReceivedWithEvent:"><em>UIResponder</em></a></blockquote><h3>Who handles the event?</h3><p>Not only the types of events should be of our interest, but also which element/control is responsible for handling the event. We have some differences in that matter between the web and iOS.</p><p>In the web, all the interaction events are first dispatched directly to the element that user interacted with, for example the mousedown event is first delivered to the innermost DOM element user clicked with her mouse. By default, all the listeners registered for that element are fired and the event is passed up the DOM hierarchy (this is called event bubbling). Every listener has the opportunity to stop the bubbling (stopPropagation) and/or cancel other listeners, but by default events traverse up to the top of the view hierarchy (to the document element), regardless if the event was somehow handled or not.</p><p>In iOS, the way the event travels up the view hierarchy is similar — it is first delivered to the control down the tree and then passed up, but only until some control actually handles it — the traversal stops then.</p><blockquote><em>calling DOM event </em><em>stopPropagation on event handling ↔ on iOS, propagation is stopped automatically when the event is handled</em></blockquote><p>Also, it is not fully accurate to say the events go up the view hierarchy. It actually go according to the <a href="https://developer.apple.com/library/prerelease/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html#//apple_ref/doc/uid/TP40009541-CH4-SW2">responder chain</a>, which might or might not be equal to the view hierarchy order of controls. For touch events, unless we modify the <a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIResponder_Class/index.html#//apple_ref/occ/instm/UIResponder/nextResponder">nextResponder property</a>, it is the same. But we might want to manage which control is the next responder on our own, for example to implement nice <a href="http://stackoverflow.com/questions/1347779/how-to-navigate-through-textfields-next-done-buttons">keyboard traversal through the text inputs</a>.</p><blockquote><em>DOM events bubble up the DOM hierarchy ↔ iOS events traverse according to the responder chain</em></blockquote><p>But there are few more quirks. First one is the way the iOS determines which control was touched — it starts from the uppermost window view and <a href="https://developer.apple.com/library/prerelease/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html#//apple_ref/doc/uid/TP40009541-CH4-SW4">performs a hit-testing</a> on its subviews recursively. That takes into consideration only the views that are <a href="https://developer.apple.com/library/ios/qa/qa2013/qa1812.html">actually visible within the view’s bounds</a> — so the views that are drawn outside its superview using clipToBounds = NO can’t handle the touch events properly. The workaround is to override <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:">the hit-testing method</a>, but this gets hairy pretty quickly.</p><blockquote><em>DOM events are delivered to the innermost element according to view hierarchy only ↔ iOS touch events are delivered to the innermost control according both to view hierarchy and position within bounds</em></blockquote><p>One more important trick that is often used to modify the default touch target control on iOS is to disable the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/userInteractionEnabled">userInteractionEnabled flag</a> for the control to prevent it being considered for hit-testing. In that case, the control that gets the event might not actually be the innermost one, but the last of its ancestors that doesn’t have interaction disabled. To achieve something a bit similar in the web, we can set CSS pointer-events: none on the element we want to “disable”, although this is rather rough analogy.</p><blockquote><em>pointer-events: none in CSS ↔ </em><em>UIView’s </em><em>userInteractionEnabled flag</em></blockquote><p>That’s all, folks. I hope anyone finds this series worth reading. I’d be grateful for any corrections, additions or just comments.</p><h3>Adam Bar</h3><p>The Web Guy @ Bright Inventions</p><p><a href="https://whatwebcando.today/">Personal blog</a> <a href="/service/mailto:adam.bar@brightinventions.pl">Email</a> <a href="http://twitter.com/NOtherDev">Twitter</a> <a href="http://github.com/NOtherDev">Github</a> <a href="http://stackoverflow.com/users/142827/notherdev">Stackoverflow</a></p><p><strong>iOS layouts for web developers #5 — events handling</strong> was published on May 21, 2015.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93f45d350a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-5-events-handling-93f45d350a0d">iOS layouts for web developers #5 — events handling</a> was originally published in <a href="https://medium.com/ios-layouts-for-web-developers">iOS layouts for web developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS layouts for web developers #4 — CSS properties replacements]]></title>
            <link>https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-4-css-properties-replacements-c4088dcbf749?source=rss----3f3469644fa1---4</link>
            <guid isPermaLink="false">https://medium.com/p/c4088dcbf749</guid>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Bright Inventions]]></dc:creator>
            <pubDate>Wed, 02 Aug 2017 09:21:15 GMT</pubDate>
            <atom:updated>2017-08-02T09:21:55.807Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth post in the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers/"><strong>iOS layouts for web developers</strong> series</a>. The previous ones were about <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-1-basic-building-blocks/">the controls</a>, <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-2-control-positioning/">control positioning</a> and <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-3-managing-appearance/">managing the appearance</a>. This time something more lightweight, I hope. We’ll go through various visual aspects of the controls and see how we can set it up, compared to CSS. Let’s start with the basics — margin and padding.</p><h3>Box model &amp; controlling controls spacing</h3><p>There was <a href="http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug">a lot of confusion</a> in the past in the web world around the box model, i.e. whether the size of an element should be calculated including or excluding its padding and border sizes. Finally, by default, the HTML element size excludes padding and borders (unless we decide to change that using box-sizing CSS property). How does it work in iOS?</p><p>Paddings and margins are not useful at all within frame-based positioning — you place the content where you place it, full stop. In the constraints-based layouts (auto layout), though, paddings and margins make a lot of sense. In most cases in iOS these concepts are known as <a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIKitDataTypesReference/index.html#//apple_ref/c/tdef/UIEdgeInsets">inset and outset</a> and are actually a single value — we get the margin (outset) effect when we use negative value, padding (inset) for positive.</p><blockquote><em>CSS padding ↔ inset, -outset</em></blockquote><blockquote><em>CSS margin ↔ outset, -inset</em></blockquote><p>In the context of auto layout, most of the controls has some natural margins (insets) set that are used automatically whenever we’re constraining to the control’s leading space (contrary to the edge). From iOS 8, new UIView property was introduced to control the inset/outset value - <a href="http://coding.tabasoft.it/ios/ios8-layout-margins/">layoutMargins</a>. It allows to control the inset (or outset, if value is negative) for each side of the control separately.</p><blockquote><em>CSS padding, margin ↔ </em><em>UIView’s </em><em>layoutMargins property</em></blockquote><p>Next thing in the box model is the border. There is no such property directly available on UIView (except for UITextField’s <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextField_Class/#//apple_ref/occ/instp/UITextField/borderStyle">borderStyle</a> property). In order to draw a border around the view, we need to rely on the lower level CALayer and use its <a href="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instp/CALayer/borderWidth">borderWidth</a> and <a href="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instp/CALayer/borderColor">borderColor</a> properties.</p><blockquote><em>CSS </em><em>border-color ↔ </em><em>layer.borderColor</em></blockquote><blockquote><em>CSS </em><em>border-width ↔ </em><em>layer.borderWidth</em></blockquote><p>So, how about the box model? In iOS, the size comes from the frame property, either assigned or calculated with constraints, regardless of the inset (layoutMargins) values or border size. Both margins and borders are drawn within a frame, so the box model on iOS actually is the same like on IE6, not like in the web nowadays.</p><blockquote><em>box-sizing: border-box ↔ the default box model in iOS</em></blockquote><blockquote><em>the web’s default </em><em>box-sizing: content-box ↔ N/A in iOS</em></blockquote><p>There is one more thing specific to iOS layouts and controls sizing that should be mentioned here. Apart from the frame, the view has the sibling <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/bounds">bounds</a> property. While frame is about the control’s size and location within the superview’s coordinate system, <a href="http://stackoverflow.com/a/11282765/142827">bounds are the values within the control’s own system</a>. It means that in most cases the control’s origin is (0,0), but it changes with rotation, scaling or translations. It makes sense to use the frame property from the context of superview when dealing with its children (when our code runs from the top - like from the view controller - looking down in the view hierarchy). On the other hand, it makes sense to use bounds when dealing with the control’s own view (for example when we’re writing the custom control), as bounds are decoupled from the specifics about where and how the view is rendered at the given point of time.</p><h3>Other positioning aspects</h3><p><strong>Overflow</strong> is used in the web to control what happens when the content in the element is larger than the element’s expected dimensions. When no dimensions is set, the elements grow with the content, so no overflow applied. Otherwise, <a href="https://css-tricks.com/the-css-overflow-property/">one of the tree options</a> applies — either the excess content is visible outside the element’s dimensions (overflow: visible, the default), cut off and invisible (overflow: hidden) or the scrollbars are added to the side of a control to enable scrolling independent from the main window (overflow: scroll and overflow: auto). The two first options are represented directly in iOS with <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/clipsToBounds">clipsToBounds property of </a><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/clipsToBounds">UIView</a> - when set to YES, the content is clipped (cut off), the default is NO, like in the web. There is no direct replacement for automatic scrolls - in case we need that, we need to take care of it manually, creating an additional <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollView_Class/">UIScrollView</a>.</p><blockquote><em>overflow: visible ↔ </em><em>clipsToBounds = NO</em></blockquote><blockquote><em>overflow: hidden ↔ </em><em>clipsToBounds = YES</em></blockquote><blockquote><em>overflow: scroll and </em><em>overflow: auto ↔ </em><em>UIScrollView</em></blockquote><p><strong>Z-Index</strong>. The position of a control on the Z-axis is quite important when we use the absolute positioning (or frame-based positioning in iOS), as controls may arbitrarily cover and be covered by other controls and relying on the order of setting up the control is too brittle to be trusted. That’s why we use z-index value in CSS. In iOS, we have the same thing hidden in the CALayer as <a href="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instp/CALayer/zPosition">zPosition</a>. To avoid the need to go to that level and deal with the fact that view hierarchy is actually <a href="http://stackoverflow.com/questions/5466116/layer-zposition-does-not-work-with-non-sibling-uiviews">not the same as layers hierarchy</a>, we should be using [superview bringSubviewToFront:subview] and [superview:sendSubviewToBack:subview] to achieve the same in imperative, but more powerful manner.</p><blockquote><em>z-index CSS property ↔ </em><em>layer.zPosition, exposed through </em><em>bringSubviewToFront and </em><em>sendSubviewToBack</em></blockquote><p>Most of the <strong>display</strong> CSS property, as known in the web, doesn’t have a lot of sense in iOS layouts, as there is no distinction between inline and block elements and there’s no document flow, as we’ve already learned. The only display value that makes any sense for iOS is none that allows to hide the element without actually removing it from the view. The UIView’s property for this purpose is conveniently called <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/hidden">hidden</a>.</p><blockquote><em>display: none ↔ </em><em>hidden</em></blockquote><h3>Backgrounds</h3><p>In iOS, there is concise <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/backgroundColor">backgroundColor</a> property that encapsulates most of background styling, much like background in CSS. At a first glance, it seems to be simple and intended for setting plain-colored backgrounds. But it’s actually much more powerful than that. UIColor class can be initialized using <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/#//apple_ref/occ/clm/UIColor/colorWithPatternImage:">colorWithPatternImage method</a> that takes an UIImage instance and the “color” it creates is actually an image that can fill our view’s background with repetition - however strange it might sound. In case we need more control over stretching, repetition etc., we need to defer to “manual” way. We need to add UIImageViewas a subview to our view and ensure it is displayed at the bottom on Z-axis.</p><blockquote><em>background-color CSS property ↔ </em><em>backgroundColor with plain color</em></blockquote><blockquote><em>background-image CSS property with </em><em>background-repeat: repeat ↔ </em><em>backgroundColorwith </em><em>UIColor created through </em><em>colorWithPatternImage</em></blockquote><blockquote><em>background-image CSS property with stretching or custom positioning ↔ </em><em>UIImageViewsubview</em></blockquote><p>Moreover, for a reason unknown to me, UITextField has <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextField_Class/#//apple_ref/occ/instp/UITextField/background">background property</a> specialized for setting and stretching the background image for a text field, so there’s no need to fall back to adding a subview in this case.</p><blockquote><em>background-image CSS property with stretching on &lt;input&gt; ↔ </em><em>background on </em><em>UITextField</em></blockquote><h3>Text properties</h3><p>As we discussed in <a href="http://brightinventions.pl/ios-layouts-for-web-developers-1-basic-building-blocks/">the first post</a> the textual content in iOS may appear only within specialized controls like <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/">UILabel</a> or controls supporting <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/">NSAttributedString</a> textual values.</p><p>NSAttributesString has <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/index.html#//apple_ref/doc/constant_group/Character_Attributes">plenty of options</a> for customizing text appearance, ranging from colors, through underlines and strikethroughs, to effects such as strokes and shadows. Some of the properties are encapsulated within <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html">NSParagraphStyle</a> available under NSParagraphStyleAttributeName key in the attributed string.</p><blockquote><em>font CSS properties combined ↔ </em><em>NSAttributedString with </em><em>NSFontAttributeName</em></blockquote><blockquote><em>text-align CSS property ↔ </em><em>alignment property of </em><em>NSParagraphStyleAttributeNamevalue in </em><em>NSAttributedString</em></blockquote><blockquote><em>text-indent CSS property ↔ </em><em>firstLineHeadIntent property of </em><em>NSParagraphStyleAttributeName value in </em><em>NSAttributedString</em></blockquote><blockquote><em>padding-left CSS property ↔ </em><em>headIndent property of </em><em>NSParagraphStyleAttributeNamevalue in </em><em>NSAttributedString</em></blockquote><blockquote><em>padding-right CSS property ↔ </em><em>tailIndent property of </em><em>NSParagraphStyleAttributeName value in </em><em>NSAttributedString</em></blockquote><blockquote><em>line-height CSS property ↔ </em><em>lineSpacing property of </em><em>NSParagraphStyleAttributeNamevalue in </em><em>NSAttributedString</em></blockquote><blockquote><em>word-wrap CSS property ↔ </em><em>lineBreakMode property of </em><em>NSParagraphStyleAttributeNamevalue in </em><em>NSAttributedString</em></blockquote><blockquote><em>color CSS property ↔ </em><em>NSAttributedString with </em><em>NSForegroundColorAttributeName</em></blockquote><blockquote><em>background-color CSS property ↔ </em><em>NSAttributedString with </em><em>NSBackgroundColorAttributeName</em></blockquote><blockquote><em>text-decoration: line-through CSS value ↔ </em><em>NSAttributedString with </em><em>NSStrikethroughStyleAttributeName set to </em><em>NSUnderlineStyleSingle</em></blockquote><blockquote><em>text-decoration: underline CSS value ↔ </em><em>NSAttributedString with </em><em>NSUnderlineStyleAttributeName set to </em><em>NSUnderlineStyleSingle</em></blockquote><blockquote><em>text-stroke CSS property (</em><a href="http://caniuse.com/#feat=text-stroke"><em>not widely supported yet</em></a><em>) ↔ </em><em>NSAttributedString with </em><em>NSStrokeColorAttributeName and </em><em>NSStrokeWidthAttributeName</em></blockquote><blockquote><em>text-shadow CSS property ↔ </em><em>NSAttributedString with </em><em>NSShadowAttributeName</em></blockquote><p>UILabel, the control dedicated for text display, supports <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/attributedText">attributedText</a>, so can handle all of the features for NSAttributedString, but additionally exposes some properties that affect the whole label content, like <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/textAlignment">textAlignment</a>.</p><blockquote><em>font CSS properties combined ↔ </em><em>UILabel’s </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/font"><em>font</em></a></blockquote><blockquote><em>color CSS property ↔ </em><em>UILabel’s </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/textColor"><em>textColor</em></a></blockquote><blockquote><em>text-align CSS property ↔ </em><em>UILabel’s </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/textAlignment"><em>textAlignment</em></a></blockquote><blockquote><em>word-wrap CSS property ↔ </em><em>UILabel’s </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/lineBreakMode"><em>lineBreakMode</em></a></blockquote><h3>Fancy effects</h3><p>Some of the “fancy” text effects like text shadows or strokes are available through NSAttributedStringwe’ve just gone through. There are few more available, though. I think “fancy effects” is not a perfect heading, anyway, but I needed a place to describe few more properties that are available in iOS and are well-known in CSS but I couldn’t fit it anywhere else. So here we go:</p><blockquote><em>opacity CSS property ↔ </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/alpha"><em>alpha</em></a></blockquote><blockquote><em>animation CSS properties family ↔ whole bunch of </em><em>UIView’s </em><a href="https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html"><em>specialized methods</em></a></blockquote><blockquote><em>border-radius CSS property for &lt;input&gt; ↔ </em><em>UITextField’s </em><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextField_Class/#//apple_ref/occ/instp/UITextField/borderStyle"><em>borderStyle</em></a><em> set to </em><em>UITextBorderStyleRoundedRect</em></blockquote><blockquote><em>border-radius CSS property in general ↔ </em><a href="https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CALayer_class/index.html#//apple_ref/occ/instp/CALayer/cornerRadius"><em>layer.cornerRadius</em></a></blockquote><p>That’s all I found useful and worth mentioning here, but of course the full list of styling-related features of UIKit, and especially when going down to CALayers is vast, likewise the full list of features in CSS, so I don’t think it’s even feasible to cover everything here.</p><p>Next time I’ll conclude the series with <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-5-events-handling/">the post about events handling</a>.</p><h3>Adam Bar</h3><p>The Web Guy @ Bright Inventions</p><p><a href="https://whatwebcando.today/">Personal blog</a> <a href="/service/mailto:adam.bar@brightinventions.pl">Email</a> <a href="http://twitter.com/NOtherDev">Twitter</a> <a href="http://github.com/NOtherDev">Github</a> <a href="http://stackoverflow.com/users/142827/notherdev">Stackoverflow</a></p><p><strong>iOS layouts for web developers #4 — CSS properties replacements</strong> was published on April 10, 2015.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4088dcbf749" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-4-css-properties-replacements-c4088dcbf749">iOS layouts for web developers #4 — CSS properties replacements</a> was originally published in <a href="https://medium.com/ios-layouts-for-web-developers">iOS layouts for web developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS layouts for web developers #3 — managing the appearance]]></title>
            <link>https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-3-managing-the-appearance-358492ed9457?source=rss----3f3469644fa1---4</link>
            <guid isPermaLink="false">https://medium.com/p/358492ed9457</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bright Inventions]]></dc:creator>
            <pubDate>Mon, 31 Jul 2017 08:10:37 GMT</pubDate>
            <atom:updated>2017-08-02T09:22:12.712Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the third part of the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers/"><strong>iOS layouts for web developers</strong> series</a>. The f<a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-1-basic-building-blocks/">irst part was about the controls</a>, the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-2-control-positioning/">second about its positioning</a>. Now I’m going to tackle how to approach managing the controls appearance — something that we have CSS for in the web.</p><h3>CSS equivalent?</h3><p>CSS was first standardised back in 1996, it was around early 2000s when it became ubiquitous. We’ve then left behind the times when the &lt;center&gt; tag was used to align content and view specific definitions like fonts or colors were scattered all over through the HTML structure. For almost two decades, we clearly feel it wasn’t the good way of doing things and we now strive to maintain the separation of structure vs. presentation. CSS is now an inseparable part of the web development, there’s virtually no way to do anything without it. It’s like a skin for the human body, we don’t rather meet anyone without one and even if we meet, we’d probably be frightened and disgusted by the raw and bloody flesh visible.</p><p>Now, it’s 2015 and we’re looking at the iOS layouts. How do we maintain the content vs. presentation separation in iOS? The short answer is — we don’t. There is no direct replacement for CSS concept in iOS. I was seriously shocked when I first learned that fact. But the fact is, a lot of iOS community <a href="http://stackoverflow.com/questions/2767512/good-reasons-why-to-not-use-xib-files?rq=1">doesn’t care</a>. Most iOS developers go <a href="http://www.techrepublic.com/blog/software-engineer/getting-started-with-ios-views-and-view-controllers-part-1/">“the Apple way”</a> here and use <a href="https://developer.apple.com/xcode/interface-builder/">Interface Builder</a> to design the layout. They define the whole presentation layer by clicking and dragging, not even feeling the need of any code for that purpose.</p><blockquote><em>content vs. presentation separation and styles reuse using CSS ↔ N/A</em></blockquote><p>One might say that less code means less bugs, but of course, Interface Builder does nothing different than generating the code underneath. It’s in <a href="http://www.monobjc.net/xib-file-format.html">XIB format</a>, nothing easily “consumable” by anything other than its native generator. Trying to touch it from the outside <a href="http://stackoverflow.com/questions/1660606/is-it-possible-to-directly-edit-the-xml-of-xib-files">will probably hurt</a>. Working with the code generator like Interface Builder <a href="http://blog.teamtreehouse.com/why-i-dont-use-interface-builder">can often encourage bad practices</a> — it creates tight coupling between view and it’s logic behind, it creates merge hell when touched by more than one person, it destroys the ability to reuse style definitions and the relation between what we did in the IDE and what we got in the final app is too implicit.</p><p>Also, maybe it’s only my personal delusion, but I think we in the web world feel a lot of disgust for WYSIWYGs in general and often even for using the mouse at all. CSS is not an imperative programming language (fortunately), but it’s still the code. We treat it as such, we edit it as a raw text files, we understand it and we feel comfortable with that fact. Whenever something automated messes with my CSS or HTML, I’m losing the confidence in what’s going on and how it works.</p><h3>How to handle style definitions then?</h3><p>When we decide not to go “the Apple way” and abandon Interface Builder striving for something that allows style definitions reuse and separation, our simplest alternative is to <a href="https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW36">create everything directly in the code</a>, instantiating the controls “manually”, setting its properties like colors, setting its frame or Auto Layout constraints and finally adding it to the superview, like this:</p><p>- (void)loadView { [super loadView]; UILabel *testView = [UILabel new]; testView.backgroundColor = [UIColor redColor]; testView.font = [UIFont boldSystemFontOfSize:24]; testView.text = @&quot;test&quot;; testView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:testView]; [testView sizeToFit]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeTopMargin relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTopMargin multiplier:1 constant:20]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:20]]; }</p><p>For complex screens, it quickly grows to hundreds of lines of imperative and repetitive code that is inherently very declarative in its real nature. It hurts me every time I assign properties like font and backgroundColoretc. It feels just like I’d be putting &lt;font face=“Arial” color=“red”&gt; in my HTML markup and it’s already more than 10 years ago when I did so the last time. It’s like that human flesh visible outside.</p><p>One simple strategy we can employ is to enclose our repeatable patterns of style and layout definitions, very remotely equivalent to our CSS classes, as a static method somewhere or as <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html">a category on </a><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html">UIView</a>:</p><p>@implementation UILabel (Layout) + (UILabel *)bigRedLabel { UILabel *label = [UILabel new]; label.backgroundColor = [UIColor redColor]; label.font = [UIFont boldSystemFontOfSize:24]; return label; } - (void)placeInTopLeftCornerOf:(UIView *)parentView { self.translatesAutoresizingMaskIntoConstraints = NO; [self sizeToFit]; [parentView addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTopMargin relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeTopMargin multiplier:1 constant:20]]; [parentView addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeLeading multiplier:1 constant:20]]; } @end</p><p>Now we can use it whenever we want our new control to look like the other:</p><p>- (void)loadView { [super loadView]; UILabel *testView = [UILabel bigRedLabel]; testView.text = @&quot;test&quot;; [self.view addSubview:testView]; [testView placeInTopLeftCornerOf:self.view]; }</p><h3>Apple proposal — appearance proxies</h3><p>The issue of style definitions reuse was also approached by Apple within UIKit, albeit quite differently than in CSS. There’s a concept called <a href="http://nshipster.com/uiappearance/">appearance</a>. It allows us to define selected style properties of the controls once per the application, ensuring any customization we do is applied consistently across the app. We can define that all the buttons (UIButton instances) that we use in our app should have gray background:</p><p>[UIButton appearance].backgroundColor = [UIColor grayColor];</p><p>We can restrict our customization scope to controls contained within another specific container control, for example to all UIBarButtonItems within UIToolbar:</p><p>[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil] .tintColor = [UIColor blackColor];</p><p>Also, we can optionally make our appearance definitions dependent on the screen dimensions and orientations, using UITraitCollections we’ve discussed <a href="http://brightinventions.pl/ios-layouts-for-web-developers-2-control-positioning/#the-real-responsiveness?">in the previous part of the series</a>:</p><p>UITraitCollection *traitCollection = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact]; [UIImageView appearanceForTraitCollection:traitCollection] .tintColor = [UIColor redColor];</p><p>Appearance might be compared to CSS limited to elements only (no per-class or per-id definitions), with basic hierarchies and basic media queries support. However, the distance to the full-blown CSS equivalent is quite large. There is no way to apply appearance definitions to the selected subset of elements of a given type, like we do using CSS classes. There is no way to represent other types of relationships between controls than ancestor-descendant (whenContainedIn) - we need to forget about the selectors we know from CSS like siblings, direct children, n-th of type and so on. Moreover, when we have multiple ancestor-descendant relationships defined, <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAppearance_Protocol/">the first one encountered (most generic) is used</a>, while in CSS the most specific one is used, allowing us to specify our styles from the general definitions to the specialized ones going down the elements tree.</p><blockquote><em>CSS definitions on HTML elements ↔ </em><a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/index.html#//apple_ref/doc/uid/TP40012857-UIView-SW16"><em>UIAppearance</em></a><em> definitions</em></blockquote><blockquote><em>CSS definitions on HTML element hierarchies ↔ UIAppearance definitions with </em><em>whenContainedIn overloads; limited</em></blockquote><blockquote><em>CSS definitions with screen size-related media queries ↔ UIAppearance definitions with </em><em>forTraitCollection overloads; limited</em></blockquote><blockquote><em>CSS features other than above ↔ N/A</em></blockquote><p>Last but not least, customization via appearance is by default limited only to <a href="https://gist.github.com/mattt/5135521">several properties of the controls</a>exposed by iOS with the UI_APPEARANCE_SELECTOR tag. For example, generic UIView only allows us to set backgroundColor through appearance and such a common control like UILabel doesn’t add anything more on its own. This means there is no out-of-the-box solution for setting text color, font properties, margins etc. for all the labels once across the application. That limitation can be overcome by defining an UI_APPEARANCE_SELECTOR <a href="http://timross.info/blog/2013/03/26/more-fun-with-uiappearance/">for custom properties</a> and <a href="http://petersteinberger.com/blog/2013/uiappearance-for-custom-views/">for custom controls</a>, but that is far from the elegance of plain old declarative CSS.</p><h3>Prospects for truly declarative solution</h3><p>There are multiple projects out there in the open source space that aims to bring the real declarativeness, style reuse possibility and overall CSS feel to iOS views. Both <a href="https://github.com/robertwijas/UISS">UISS</a> and <a href="https://github.com/tombenner/nui">NUI</a> offer the syntax loosely inspired by CSS. The former is just a wrapper for UIAppearance with all its limitations. The latter goes much further, actually taking care of virtually all the styling exposed by UIKit controls. There are also <a href="http://pixate.github.io/pixate-freestyle-ios/">Pixate Freestyle</a> and <a href="http://nativecss.com/">nativeCSS</a> that offer direct usage of CSS within iOS apps. In Bright we’re also doing some in-house experiments in <a href="https://github.com/bright/Cero">Cero</a>, albeit it aims more to provide the declarative view hierarchy and the styling comes a bit as a side effect.</p><p>The most advanced solutions that features declarative and reusable styles are probably offered by the cross-platform frameworks that originate from the web. These frameworks promise the web developers a way to reuse some of our JavaScript, HTML and CSS skills directly on mobile platforms to produce native or semi-native experiences. Users of the platforms that employ HTML directly as a language to define apps views, like <a href="http://coenraets.org/blog/phonegap-tutorial/">PhoneGap/Cordova</a>, <a href="http://ionicframework.com/docs/components/">Ionic</a> or <a href="http://www.idangero.us/framework7/">Framework7</a> immediately benefit from having the real power of CSS available. Of course it comes with the penalty of being a thick and often limited or leaky abstraction.</p><p>On the other side there are frameworks that offer their own abstractions on views and styles. The one that <a href="http://www.objc.io/issue-22/facebook.html">seems quite interesting</a> is <a href="https://github.com/facebook/componentkit">ComponentKit by Facebook</a>. It redefines the views in terms of components with declarative and composable API and <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes">flexbox</a>-enabled styling. One more example can’t be missed here — there is a lot of buzz around recently released <a href="http://jlongster.com/First-Impressions-using-React-Native">React Native</a> framework that offers its own approach of using JavaScript (and JSX known from <a href="https://facebook.github.io/react/">React.js</a>) natively in iOS. With the power of JavaScript we’re familiar with, we can shape and reuse our presentation code in a more elegant way. React Native uses a <a href="http://facebook.github.io/react-native/docs/style.html#content">lightweight version of CSS</a> that offers features like <a href="https://facebook.github.io/react-native/docs/style.html#content">composition</a> and <a href="https://facebook.github.io/react-native/docs/flexbox.html">flexbox</a>.</p><p>I believe that all of these ideas and frameworks are shaping the future of iOS layouts and are worth keeping an eye on it with the hope that someday the native offering of iOS platform in terms of managing the appearance would not be so limited as today.</p><p>Next time — more on <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-4-css-properties-replacements/">how to achieve particular visual effects known from CSS within iOS views</a>.</p><h3>Adam Bar, The Web Guy @ Bright Inventions</h3><p><a href="https://whatwebcando.today/">Personal blog</a> <a href="/service/mailto:adam.bar@brightinventions.pl">Email</a> <a href="http://twitter.com/NOtherDev">Twitter</a> <a href="http://github.com/NOtherDev">Github</a> <a href="http://stackoverflow.com/users/142827/notherdev">Stackoverflow</a></p><p><strong>iOS layouts for web developers #3 — managing the appearance</strong> was published on April 03, 2015.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358492ed9457" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-3-managing-the-appearance-358492ed9457">iOS layouts for web developers #3 — managing the appearance</a> was originally published in <a href="https://medium.com/ios-layouts-for-web-developers">iOS layouts for web developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS layouts for web developers #2 — control positioning]]></title>
            <link>https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-2-control-positioning-bea79ee2e68?source=rss----3f3469644fa1---4</link>
            <guid isPermaLink="false">https://medium.com/p/bea79ee2e68</guid>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[autolayout]]></category>
            <dc:creator><![CDATA[Bright Inventions]]></dc:creator>
            <pubDate>Fri, 28 Jul 2017 08:03:08 GMT</pubDate>
            <atom:updated>2017-08-02T09:22:24.779Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-1-basic-building-blocks/">first part</a> of the <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers/"><strong>iOS layouts for web developers</strong> series</a> I’ve discussed controls as the basic building blocks that comprises the layout in iOS world and how that compares to HTML. I haven’t tackled anything about how and where these controls are drawn on the screen. The matter is complex enough so that here is the separate post only about it.</p><p>Let’s start with restating the acknowledgement that my overall goal here is trying to find best analogies to the web development world, not creating an ultimate guide to how those things should generally be done in iOS. Some approaches that are natural in HTML might be considered bad practice or at least not idiomatic in iOS.</p><p>I’ll start from frame-based positioning that is historically the first approach available in iOS, but no longer considered the best one. But I can’t just skip it, primarily because there are a lot of analogies to the web and also because in order to fully embrace the newer approaches one should at least understand the primitives. It’s like one can’t really do good responsive web design lacking the ability to prepare static non-responsive layout.</p><h3>Where is my control?</h3><p>In HTML, when we don’t set any sizes nor positions for the block element, it is drawn according to the <a href="http://webdesign.tutsplus.com/articles/quick-tip-utilizing-normal-document-flow--webdesign-8199">normal document flow</a> — we’ll find it next to the previous element in the document structure, sized according to the size of its child elements. The thing that struck me most when I was starting with iOS is that there is no such concept there — controls just don’t show up by default, unless we tell them explicitly where should they go and what size they should take.</p><blockquote><em>normal document flow ↔ N/A</em></blockquote><blockquote><em>document flow alterations like </em><em>float, </em><em>display, </em><em>clear CSS properties ↔ N/A</em></blockquote><p>In iOS, we must explicitly control position and size of each control. Traditionally, this is done using frames. Frame is a rectangle the control takes on the screen, defined with its top-left corner coordinates within the superview, width and height. We set the frame through Interface Builder, or, if we’re creating views in the code, we either use <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/initWithFrame:">initWithFrame</a> initializer conventionally available for all the controls or set the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/frame">frame</a>property for existing control instance.</p><p>Frame-based positioning is quite directly equivalent to the absolute positioning in the web, with all its deficiencies. We lack flexibility, we have no way to adjust to different screen sizes and we always need to operate in fixed-sized coordinate plane. In the web, we strive not to use absolute positioning, unless absolutely needed (pun intended). Generally, we should try to avoid it in iOS, too. We’ll see how is that possible later in this post.</p><blockquote><em>position: absolute in CSS ↔ the default, frame-based positioning</em></blockquote><p>Second aspect the iOS control’s frame is taking care of is the control’s size. The controls don’t have any default size. Unless we do something with it, every view is 0x0 in size yielding it not really useful. In the web world every element by default is sized to make room for the content within — either the text or another elements. We can customize it through CSS, but if we throw the stylesheet away, we’d still get something visible.</p><p>For some controls that have natural (intrinsic) size available, like <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/">UILabel</a> or <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImageView_Class/">UIImageView</a>, we might mitigate the need to use that pesky frame initialization using <a href="http://doing-it-wrong.mikeweller.com/2012/07/youre-doing-it-wrong-2-sizing-labels.html">sizeToFit</a> method that sets the width and height of the frame to the natural size of the content.</p><blockquote><em>width &amp; </em><em>height properties in CSS ↔ the default, frame-based sizing</em></blockquote><blockquote><em>the default, auto-sizing for elements ↔ </em><em>sizeToFit method for some controls</em></blockquote><h3>First take on “responsive” layouts</h3><p>Frame-based layout is very limiting, but it was <a href="http://wiki.c2.com/?DoTheSimplestThingThatCouldPossiblyWork">the simplest thing that could possibly work,</a> especially given the fact that it was first designed for a single size of a single device — the first-generation iPhone. The need for “responsiveness”, as we like to call it in the web world, was limited to screen rotation. When iPads came, there still weren’t many apps that share the same layouts between two form factors. It’s only quite recently, with the introduction of iPhone 5 that was taller than the previous ones and especially with iPhone 6 that comes with two <a href="http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions">totally distinct screen resolutions</a>, there’s a real push toward having a single layout shared between screen sizes and resolutions — something that is obvious for the modern web development.</p><p>Before iOS 6 (released in 2012), the only mean of “responsiveness” was the notion of <a href="http://www.techpaa.com/2012/05/understanding-uiview-autoresizing.html">autoresizing mask</a>accessible via UIView’s <a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/autoresizingMask">autoresizingMask</a> property. It allows to set which dimensions or spacing attributes should be kept and which can be modified on screen size change (rotation, basically). For example, when “flexible width” is set, on rotation, the horizontal margins widths are persisted and the control width takes the rest of available space. When, in turn, “flexible left margin” is set, the width wouldn’t change and the left margin will take all the space that’s still available.</p><p>That technique is quite natural and comes automatically in the web. One way to get the flexibility alike is to use percentage dimensions in CSS. Another way, for absolutely-positioned elements, is not to set one of the dimension to make it flexible. As an example, not setting the width while setting both left and right property will result in the same “autoresizing” behavior than setting UIViewAutoresizingFlexibleWidth in iOS.</p><blockquote><em>percentage values in CSS ↔ autoresizing mask</em></blockquote><blockquote><em>absolute positioning with not all dimensions fixed ↔ autoresizing mask</em></blockquote><h3>Auto layouts</h3><p>The next approach to push frame-based layouts into obsolescence is <a href="http://www.informit.com/articles/article.aspx?p=2041295">Auto Layout</a>, introduced with iOS 6. It is very powerful, flexible and well-thought system of constraints that one may define on the dimension and position-related attributes of the view, optionally with relation to the other views. What it means is that we may for example define that the left edge of our view is to be placed at the right edge of another view with some outset given, and the top edge of our view should be centered within its superview, and so on. Generally, we create a set of linear equations to calculate views attribute values out of another attribute values and the system tries to satisfy those equations when drawing the controls on the screen. If that succeeds, we end up with a nicely adaptive layout.</p><p>This approach can be used to emulate web’s relative positioning when we set the constraints on the child view according to the position and size of the chosen superview. But Auto Layout gives us even more. The constraints can be set between arbitrary attributes of arbitrary views, as long as these views have a common ancestor. We can constraint the values not only to be equal, but also to be smaller (or greater) — this allows us to achieve what we do in CSS with max-width property and its family. Next, we’re not limited to the parent-child relationship - we can relate siblings, for example to put one next to another, emulating CSS floating. Note also that it’s nothing unusual to set constraints on the view’s bottom edge - that was quite unnatural for me as I rarely use bottom property in CSS. With Auto Layout we can even do tricks like sticking each edge of our view to different attribute of different views. Imagination and maths are the only limits here.</p><blockquote><em>relative positioning ↔ can be emulated with Auto Layout by constraining child views to parents</em></blockquote><blockquote><em>min-height, </em><em>min-width and similar ↔ can be emulated with Auto Layout by setting constraints with inequalities</em></blockquote><blockquote><em>float-based positioning ↔ can be emulated with Auto Layout by constraining sibling views</em></blockquote><h3>The real responsiveness?</h3><p>While Auto Layout is a great and powerful tool that sometimes even outpaces the techniques and approaches known from the web to achieve flexibility, in some cases it was still impossible or at least cumbersome to define a single layout for all the screen form factors available, especially for both iPad and iPhone. Similarly to the web, when we’re utilizing the responsive web design principles, we’re not just scaling and rearranging the elements. More than often we differentiate what and where we show some parts of the layout using <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries">media queries</a> and its <a href="https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/how-to-choose-breakpoints">breakpoints</a>, most commonly based on the screen width.</p><p>iOS 8 introduced the concept of <a href="http://www.imore.com/adaptive-ui-ios-8-explained">Adaptive UI</a> that is aimed to achieve something similar — allow reorganizing layouts for various screen sizes and orientations. Views and view controllers got a new <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITraitEnvironment_Ref/index.html#//apple_ref/occ/intfp/UITraitEnvironment/traitCollection">traitCollection</a>property that exposes <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITraitCollection_ClassReference/">UITraitCollection</a> instance, keeping current screen size factors, so we can code against the current values. Similar interface is exposed to work with appearances (we’ll discuss appearances next in the series, when we talk about CSS alternatives for iOS). Probably more useful part is the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITraitEnvironment_Ref/index.html#//apple_ref/occ/intfm/UITraitEnvironment/traitCollectionDidChange:">traitCollectionDidChange event</a> triggered on the screen rotation (actually, it is called “when the iOS interface environment changes”, it will be even more useful in case Apple introduces a resizable device) - we can provide a custom behaviors like changing the view hierarchies or Auto Layout constraints there. But probably the most benefit one gets from the Adaptive UI surfaces through the <a href="http://www.bignerdranch.com/blog/iOS-8-demo-universal-storyboards-and-adaptive-ui/">Interface Builder’s storyboards</a>that are now aware of the traits and allow us to have an universal storyboard that works across multiple form factors.</p><p>Unfortunately, Adaptive UI is far less flexible than CSS media queries. We have only few preset and quite abstract “size classes” available — compact vs. normal for width, compact vs. normal for height and scale factor value. It might not be sufficient precision for all the needs we could have. For example, the width is marked as “compact” for iPhone both in horizontal and vertical orientation and for iPad both dimensions are “normal” regarding of the orientation. Although customizing the breakpoints <a href="https://iosdevweek.ly/k6qFtrd?sid=VPi2m9y">is possible</a>, it’s a bit off the “Apple way” of doing things and certainly not as handy as using the defaults.</p><blockquote><em>CSS media queries based on screen size ↔ partially covered by Adaptive UI trait collection</em></blockquote><p>Next time in the series —<a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers-3-managing-appearance/"> more about CSS equivalents in iOS (or lack of such).</a></p><h3>Adam Bar, The Web Guy @ Bright Inventions</h3><p><a href="https://whatwebcando.today/">Personal blog</a> <a href="/service/mailto:adam.bar@brightinventions.pl">Email</a> <a href="http://twitter.com/NOtherDev">Twitter</a> <a href="http://github.com/NOtherDev">Github</a> <a href="http://stackoverflow.com/users/142827/notherdev">Stackoverflow</a></p><p><strong>iOS layouts for web developers #2 — control positioning</strong> was published on March 24, 2015 and last modified on March 24, 2015.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bea79ee2e68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-2-control-positioning-bea79ee2e68">iOS layouts for web developers #2 — control positioning</a> was originally published in <a href="https://medium.com/ios-layouts-for-web-developers">iOS layouts for web developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS layouts for web developers #1 — basic building blocks]]></title>
            <link>https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-1-basic-building-blocks-be6599cc493b?source=rss----3f3469644fa1---4</link>
            <guid isPermaLink="false">https://medium.com/p/be6599cc493b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Bright Inventions]]></dc:creator>
            <pubDate>Thu, 27 Jul 2017 08:00:19 GMT</pubDate>
            <atom:updated>2017-08-02T09:22:39.103Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of <a href="http://brightinventions.pl/blog/ios-layouts-for-web-developers/"><strong>iOS layouts for web developers</strong> series</a> I’ll have a look at the basic building blocks of the view layer in iOS and compare it to what HTML offers. First, we need to shift our mindset a bit and accept the fact we need to give up some control (pun intended) over our views to the iOS.</p><h3>Elements vs. controls</h3><p>In HTML, everything we can see in the browser is built upon the low-level HTML elements (tags) organized within a hierarchy. The browser draws the elements visual representations according to the associated CSS stylesheet definitions, intrinsic size of the content within a control and the document flow.</p><p>In iOS for composing views we’re mostly using the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKit_Framework/">UIKit framework</a>. What we see on the screen also comprises a hierarchy — its elements are <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/">UIView</a> instances or instances of its subclasses. View is a concept on the higher level of abstraction than single HTML element. UIView is the generic building block, it may be thought of as &lt;div&gt; equivalent - by default it serves as just a container to hold another elements, but it’s visual aspects can be freely customized.</p><blockquote><em>&lt;div&gt; ↔ </em><em>UIView</em></blockquote><p>UIKit offers a lot of out-of-box functionality available as controls. All specialized controls are implemented as UIView subclasses. In most cases, controls can’t be treated as an equivalent of HTML elements. Controls conveys both visual and functional aspects - it encapsulates it together in a way more similar to Web Components or widgets than a single HTML tag. The <a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/">catalog of ready-to-use built-in controls</a> resembles <a href="http://jqueryui.com/">jQuery UI</a> library - there are popups, buttons, sliders, activity indicators etc. Also, the environment specifics of iOS controls make it less concerned about semantics, as we have much less interoperability or compatibility constraints than in the open and unbounded web development. iOS control’s concern is about how it looks and behaves like, not what role it fulfils and what meaning it conveys to the structure of the screen.</p><blockquote><em>Web Component, jQuery UI widget ↔ UIKit control (</em><em>UIView subclass)</em></blockquote><p>Because of the different level the view elements in iOS are defined compared to HTML, it’s not easy to create a translation table indicating what is the equivalent iOS control for the particular HTML element or set of elements. But let me try for the few basic ones.</p><p>First of all, it is worth noting that UIView, as the basic building block for iOS views, is powerful and configurable enough to achieve a lot itself. In HTML, there is a lot of block elements defined primarily for its semantical meaning - starting from document structure indicators like &lt;section&gt;, through &lt;address&gt;semantic blocks carrying some basic styling rules, up to &lt;hr&gt; to divide the content with the visual demarcator. In iOS, all these would be replaced with properly styled UIView (or its subclass <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/">UIControl</a> that adds some basic control events handling, if this is necessary), stripped from its semantics. It feels a bit like using &lt;div&gt;s for everything, but aspects like accessibility are not within the primary focus here, it seems.</p><blockquote><em>most of block-level elements ↔ just </em><em>UIView/</em><em>UIControl</em></blockquote><h3>Lists and tables</h3><p>The first apparently obvious direct replacement for an HTML element could be <a href="http://www.idev101.com/code/User_Interface/UITableView/">UITableView</a> for &lt;table&gt;structures. But it’s not that simple. UITableView should be more correctly called “UIListView” as in its basic form it is single column view - each row comprises a single cell. It’s main use case is to enable drill-down interface navigation style. It has nothing to do with the notion of tabular data, it is also widely and deliberately used as presentational element. Far from what we’re used to in HTML. Those aspects make UITableViewsomething more equivalent to popular use case for &lt;nav&gt; or &lt;ul&gt; lists.</p><blockquote><em>&lt;nav&gt;, </em><em>&lt;ul&gt; for navigational purposes ↔ </em><em>UITableView and its </em><em>UITableViewCells</em></blockquote><p>Unfortunately, to emulate a real grid using UITableView, we’d need to nest custom views within a single <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewCell_Class/">UITableViewCell</a> (that is, a view for a single row) - nothing available directly out-of-the-box. But UITableView also offers some aspects that are typical for tables and is known for us from what HTML offers - header rows, table headers &amp; footers. Each of these table elements can be customized or even use an arbitrary custom view.</p><blockquote><em>&lt;th&gt; rows ↔ section header in </em><em>UITableView</em></blockquote><blockquote><em>&lt;thead&gt;, </em><em>&lt;tfoot&gt; ↔ table header &amp; table footer in </em><em>UITableView</em></blockquote><p>There is also an <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/">UICollectionView</a> thing that is supposed to display a collection of items in more flexible manner - in the most cases it forms a grid of customizable <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewCell_class/">UICollectionViewCell</a>s. It behaves like a set of elements with CSS float - it tries to put elements next to each other and wraps down when there’s no more space available. It’s still not real tabular data equivalent, but at least we’re not constrained to a single column layout.</p><blockquote><em>set of elements with </em><em>float CSS property ↔ </em><em>UICollectionView and its </em><em>UICollectionViewCells</em></blockquote><p>So what is the real equivalent of HTML tables? There’s nothing available out of the box, you need to resort to <a href="http://cocoapods.org/?q=grid">specialized controls available</a>. The separate broad topic here is how to present the tabular data effectively on the phone screen. I guess there are valid usability-related reasons to avoid tables at all.</p><blockquote><em>full-blown </em><em>&lt;table&gt; ↔ N/A</em></blockquote><h3>Forms and inputs</h3><p>By default, the data entry and manipulation in HTML is handled within request-response cycles. One need to set up the values, hit “Save” and wait for the changes to be applied. On mobile platforms we’re used to another approach — things are saved immediately after the change happened, no “Save” button needed. That reduced the need for the equivalent of &lt;form&gt; demarcator element to exist. Form controls may be placed in any hierarchy and the application is responsible to handle the values changes on each control separately. Also, in iOS, there is no built-in fields grouping</p><blockquote><em>&lt;form&gt; ↔ N/A</em></blockquote><blockquote><em>&lt;input type=“hidden”&gt;, </em><em>&lt;input type=“submit”&gt;, </em><em>&lt;input type=“reset”&gt; ↔ N/A</em></blockquote><p>The <a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIControl.html">form controls set</a> from the visual point of view is more specialized in iOS than in pure HTML. There are distinct controls designed to input certain types of data, like <a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIDatePicker.html">dates</a> or <a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UISlider.html">numerical values</a>. It is also covered by HTML5 specialized <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">input types</a>, but default UI is far simpler and not all cases are implemented even in the newest browsers.</p><p>Most textual input is based on <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextField_Class/">UITextField</a> that enables setting specific keyboardType to handle our expected content type best. For non-text inputs we have a set of standard widgets and our iOS users are already pretty used to its UX, so we should rather conform to that instead of precisely simulating something we know from web development.</p><blockquote><em>&lt;button&gt;, </em><em>&lt;input type=“button”&gt;, </em><em>&lt;a&gt; with </em><em>display: block ↔ </em><em>UIButton</em></blockquote><blockquote><em>&lt;input type=“checkbox”&gt; ↔ </em><em>UISwitch</em></blockquote><blockquote><em>&lt;input type=“radio”&gt;, </em><em>&lt;select&gt; ↔ </em><em>UIPickerView, </em><em>UIActionSheet, </em><em>UISegmentedControl</em></blockquote><blockquote><em>&lt;input type=“text”&gt; ↔ </em><em>UITextField</em></blockquote><blockquote><em>&lt;textarea&gt; ↔ </em><em>UITextView</em></blockquote><blockquote><em>&lt;input type=“password”&gt; ↔ </em><em>UITextField with </em><em>secureTextEntry = YES</em></blockquote><blockquote><em>&lt;input type=“range”&gt; ↔ </em><em>UISlider, </em><em>UIStepper</em></blockquote><blockquote><em>&lt;input type=“email”&gt; ↔ </em><em>UITextField with </em><em>keyboardType = UIKeyboardTypeEmailAddress</em></blockquote><blockquote><em>&lt;input type=“url”&gt; ↔ </em><em>UITextField with </em><em>keyboardType = UIKeyboardTypeURL</em></blockquote><blockquote><em>&lt;input type=“tel”&gt; ↔ </em><em>UITextField with </em><em>keyboardType = UIKeyboardTypePhonePad</em></blockquote><blockquote><em>&lt;input type=“number”&gt; ↔ </em><em>UITextField with </em><em>keyboardType = UIKeyboardTypeDecimalPad</em></blockquote><blockquote><em>&lt;input type=“search”&gt; ↔ </em><em>UITextField with </em><em>keyboardType = UIKeyboardTypeWebSearch</em></blockquote><blockquote><em>&lt;input type=“date”&gt; ↔ </em><em>UIDatePicker with </em><em>datePickerMode = UIDatePickerModeDate</em></blockquote><blockquote><em>&lt;input type=“time”&gt; ↔ </em><em>UIDatePicker with </em><em>datePickerMode = UIDatePickerModeTime</em></blockquote><blockquote><em>&lt;input type=“datetime”&gt; ↔ </em><em>UIDatePicker with </em><em>datePickerMode = UIDatePickerModeDateTime</em></blockquote><p>One important type of HTML input we’ve left is &lt;input type=“file”&gt; that allows us to upload a file to the web server. There is no direct equivalent in iOS because of the specifics of mobile platforms. We should not expect our users to even be aware that they have some “files” on their phones. What we can expect instead, for example, is to choose a photo from the gallery or take a new one using the camera built-in into their device. iOS provides ready-to-use component for that - <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerController_Class/">UIImagePickerController</a>. If we need something less standard, we’d need to resort to 3rd-party controls.</p><blockquote><em>&lt;input type=“file”&gt; for images ↔ </em><em>UIImagePickerController</em></blockquote><h3>Images and drawings</h3><p>To display an image in HTML, we use either &lt;img&gt; if the image is part of the content or CSS background-image if the image has purely presentational purpose. In iOS we do not have that semantic distinction, again, and although we can also <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/clm/UIColor/colorWithPatternImage:">put images into backgrounds</a>, in most cases we just use <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImageView_Class/">UIImageView</a> control. It gets <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/">UIImage</a> instance, in most cases initialized with the name of the resource we want to use. Out of the box, the image with correct resolution depending on the device screen dimensions is used, if available - something we’re still in early adoption phase in HTML with <a href="http://html5hub.com/html5-picture-element/">&lt;picture&gt; element</a>.</p><blockquote><em>&lt;img&gt;, </em><em>&lt;picture&gt; ↔ </em><em>UIImageView</em></blockquote><p>In case we need to draw something dynamically or just put some shape on the screen without resorting to images, in iOS we can always go one abstraction level deeper. Every UIView has its underlying <a href="http://www.raywenderlich.com/2502/calayers-tutorial-for-ios-introduction-to-calayers-tutorial">CALayer</a>structure. All the views are built upon CALayers. A layer represents the drawable rectangle on the screen that can be freely manipulated. It allows us to add shadows, borders, corner radius etc., so it might be seen as a replacement for some parts of CSS. There is also even lower level API available - <a href="http://www.raywenderlich.com/32283/core-graphics-tutorial-lines-rectangles-and-gradients">Core Graphics framework</a>. It corresponds more to what &lt;canvas&gt; offers, but is available for every control.</p><blockquote><em>CSS shadows, borders, corner radius etc. ↔ </em><em>CALayer</em></blockquote><blockquote><em>&lt;canvas&gt; ↔ Core Graphics functions</em></blockquote><h3>Inline elements equivalents</h3><p>There is no view markup in iOS, so naturally there is no such thing as “free” textual content we know from HTML. All the text we want to display needs to be placed within some control, most likely within <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/">UILabel</a>. From the web developer standpoint, it behaves like a block element - it has its intrinsic size and needs to be positioned, so it’s more like &lt;p&gt; with display: block. It also enables us to manipulate a lot of formatting aspects of the text block, standing in place of some text-formatting aspects of CSS and inline text elements like &lt;em&gt;, &lt;strong&gt; etc.</p><blockquote><em>&lt;p&gt; with </em><em>display: block ↔ </em><em>UILabel</em></blockquote><p>Moreover, thanks to the <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/">NSAttributedString</a> construct set via <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/attributedText">attributedText</a> property, it actually allows even parts of the text to look differently, making it equivalent to the whole soup of various HTML tags and content at once. But one have to admit, while <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/Articles/standardAttributes.html">this is powerful</a>, the code <a href="http://ios.eezytutorials.com/nsattributedstring-by-example.php">gets hairy pretty quickly</a>, not to mention how <a href="http://stackoverflow.com/questions/22854922/translate-attributed-string">cumbersome</a> is to localize it while operating on substring ranges directly. But there’s a nice workaround that will please us, web developers - a way to <a href="http://stackoverflow.com/questions/4217820/convert-html-to-nsattributedstring-in-ios">create </a><a href="http://stackoverflow.com/questions/4217820/convert-html-to-nsattributedstring-in-ios">NSAttributedString directly from HTML</a>. It has some drawbacks, but we may give it a try.</p><blockquote><em>&lt;em&gt;, </em><em>&lt;i&gt;, </em><em>&lt;strong&gt;, </em><em>&lt;b&gt;, </em><em>&lt;small&gt;, </em><em>&lt;big&gt; ↔ </em><em>NSAttributedString with </em><em>NSFontAttributeName</em></blockquote><blockquote><em>&lt;mark&gt; ↔ </em><em>NSAttributedString with </em><em>NSBackgroundColorAttributeName</em></blockquote><blockquote><em>&lt;sub&gt;, </em><em>&lt;sup&gt; ↔ </em><em>NSAttributedString with </em><em>NSSuperscriptAttributeName</em></blockquote><blockquote><em>&lt;ins&gt;, </em><em>&lt;del&gt; ↔ </em><em>NSAttributedString with </em><em>NSUnderlineStyleAttributeName</em></blockquote><p><a href="http://brightinventions.pl/ios-layouts-for-web-developers-2-control-positioning/">Next time we’ll try to tackle controls positioning</a>. Stay tuned!</p><h3><strong>Adam Bar, The Web Guy @ Bright Inventions</strong></h3><p><a href="https://whatwebcando.today/">Personal blog</a> <a href="/service/mailto:adam.bar@brightinventions.pl">Email</a> <a href="http://twitter.com/NOtherDev">Twitter</a> <a href="http://github.com/NOtherDev">Github</a> <a href="http://stackoverflow.com/users/142827/notherdev">Stackoverflow</a></p><p><strong>iOS layouts for web developers #1 — basic building blocks</strong> was published on February 27, 2015 and last modified on February 27, 2015.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be6599cc493b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-layouts-for-web-developers/ios-layouts-for-web-developers-1-basic-building-blocks-be6599cc493b">iOS layouts for web developers #1 — basic building blocks</a> was originally published in <a href="https://medium.com/ios-layouts-for-web-developers">iOS layouts for web developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>