iOS today view widgets and margins

One of the toughest things I’ve had to deal with while working on an app has been the today view widget. The widget I’ve been working on is very simple: 2 buttons and a label. Yet, there were a couple of issues I kept running into.

  1. When loading the widget, my buttons will appear and layout. With a button tap, the two buttons change size to what is constrained in the Storyboard. This only happens when the widget is loaded and with the first tap. Subsequent taps don’t affect it again.
  2. The widget, as much as I tried, would not appear as it did in the storyboard. Things weren’t centered properly.

The first item I still haven’t solved. The issue that ended up solving the second item is what I thought was affecting the button layout. Essentially, here is what I had: left button is x points from the left edge of the view, is y points from the right button, and has a width equal to the right button. The right button is the same except it has a constraint to the right edge of the view instead of the left. I had hoped that this would lead to a dynamic button size that would change on various devices and widths. Unfortunately, the small issue with the resizing buttons kept bothering me. If someone can figure this out, let me know.

The second issue was actually fairly easy to figure out. If you look at any of your current widgets, you probably notice two different layouts: ones that are full width, and ones that start indented.

I thought that Apple wanted all widgets indented, but there are even some of Apple’s own widgets that are full width. While it wouldn’t solve the first issue I was having (and gave up on), it did impact why the storyboard, set to the width of the device, wasn’t looking like what my widget was showing.

To solve this, make use of the NCWidgetProviding protocol. There is a method called widgetMarginInsetsForProposedMarginInsets  that you can use to either accept the default margin or set it to a custom value.

- (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets
{
    return UIEdgeInsetsZero;
}

By removing the insets, I suddenly had a widget that not only was centered but also was taking up the space in the view as it was in the Storyboard.

If you want to see what I was working on, check out Countr on the App Store.

Leave a Reply

Your email address will not be published. Required fields are marked *