跳至主要内容

Programmatic UIView Positioning With Rotation

原文链接

In a previous post titled, So Long, Storyboards!, I mentioned how to size and position views programmatically. However, what I didn’t realize at the time was that screen rotation failed miserably. The code samples I supplied positioned the views relative to each other but the coordinates remained the same during rotation, turning this:
iOS sample app in portrait view
Into this:
iOS sample app in landscape view with bad positioning
Which, after some kajiggering, I managed to transform into this:
iOS sample app in landscape view with proper positioning
So, how do we get started?
The first thing you’ll notice right away is that one of the views is missing in landscape mode. This was a decision I made based on the fact that it didn’t really fit properly in landscape mode anymore and I didn’t know what else to do with it. This also served as an example of one thing to do when the views are dynamic and there isn’t enough space on the screen: hide unnecessary elements.
A few choices I can think of off the top of my head would be:
  • Throw everything into a scroll view and kept the positioning more or less the same.
  • Resize the views to make them fit better / collapse views if possible
  • Hide/show views based on whether or not they are necessary in that view.
  • Disallow rotation all together. This way if they turn the device nothing happens.
The decision of what to do mainly depends on the situation and in my case they were just a bunch of boxes that served no purpose. In a real app, you’d probably want to spend more time to think about what you might want to do in that situation.

Implementation

The trick to implementing this lies in a couple of methods:
These methods are fired when the screen changes size. From the Apple UIViewController docs - Handling View Rotations:
When a rotation occurs for a visible view controller, the willRotate(to:duration:)willAnimateRotation(to:duration:), and didRotate(from:) methods are called during the rotation. The viewWillLayoutSubviews() method is also called after the view is resized and positioned by its parent. If a view controller is not visible when an orientation change occurs, then the rotation methods are never called. However, the viewWillLayoutSubviews() method is called when the view becomes visible. Your implementation of this method can call the statusBarOrientation method to determine the device orientation.
My decision to implement viewWillLayoutSubview() was based on some sample Google iOS code that implemented layoutSubviews() in the UIViewcontext.
I actually kept a lot of the sizing for the views in their closures:
lazy var cantTouchThisButton: UIButton! = {
  let button = UIButton(type: .system)
  button.setTitle("Can't touch this!!", for: .normal)
  button.sizeToFit()

  button.addTarget(self, action: #selector(cantTouchThisButton_tapped),
                   for: .touchUpInside)

  return button
}()

lazy var instructionsLabel: UILabel! = {
  let label = UILabel(frame: .zero)
  label.text = "To use this app, please check the link in the other thingamabob"
  label.numberOfLines = 0
  label.textAlignment = .center

  // set width to 75% of current view's width
  let width = self.view!.bounds.size.width * 0.75
  let size = label.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))

  var frame = label.frame
  frame.size = size
  label.frame = frame

  return label
}()

lazy var framedLabel: UILabel! = {
  let label = UILabel(frame: CGRect(x: 50, y: 70, width: 100, height: 100))

  label.backgroundColor = .gray

  return label
}()
but I removed all of the positioning code.
Now since I haven’t done much of this yet I’m still not sure how I feel about splitting up the code. It’s very possible that when rotating the sizes of the views would be expected to change as well.
I’d say it even makes sense to just initialize everything with the best designated initializers available i.e., init(frame:) for most views, then pass it .zero. Then set up all the event handlers, addTarget()UIGestureRecognizers, etc. inside the closures. Maybe even do sizeToFit() if it makes sense. But for anything that will change size dynamically, do that and the positioning both in your viewWillLayoutSubviews() life cycle method, which in my example now looks like this:
/**
 * Repositions views accordingly, without using constraints
 */
override func viewWillLayoutSubviews() {
  // point positioned label is static from the top,
  // if it wasn't I couldn't call it a point positioned view anymore :|
  self.pointPositionedLabel.frame.origin = CGPoint(x: 160, y: 70)

  // the framed label is basically tied to the nav bar
  // with a set x coordinate.
  self.framedLabel.frame.origin = CGPoint(x: 50,
      y: self.navigationController!.navigationBar.frame.maxY + 6)

  if UIDevice.current.orientation == .portrait {
    // the center positioned label goes below the framedLabel
    // if we're in landscape, that obfuscates the instructions label
    // and can't touch this button so don't show it
    self.centerPositionedLabel.isHidden = false
    self.centerPositionedLabel.frame.origin = CGPoint(
        x: self.view.frame.midX - (self.centerPositionedLabel.frame.width / 2),
        y: self.framedLabel.frame.maxY + k.VIEW_MARGIN)
  }
  else {
    self.centerPositionedLabel.isHidden = true
  }

  // instructions label is center aligned
  self.instructionsLabel.center = self.view.center

  // can't touch this button goes below the instructions label.
  self.cantTouchThisButton.frame.origin = CGPoint(
      x: self.view.frame.midX - (self.cantTouchThisButton.frame.width / 2),
      y: self.instructionsLabel.frame.maxY + k.VIEW_MARGIN)

}

Adding a Pinch of Syntactic Sugar

The code above works, however it could be cleaner. The more DRY way of handling this would be to create some category methods.
I’ve created a small few for demonstration purposes:
//
//  View+Position.swift
//
//  A limited example of how to simplify programmatic view placement and sizing
//
//  NOTE: I HAVE NOT THOROUGHLY TESTED THIS CODE. IT MAY PRODUCE BUGS. USE AT
//        YOUR OWN RISK
//
//  NoStoryboard
//
//  Created by Gregory McQuillan on 1/7/17.
//  Copyright © 2017 One Big Function. All rights reserved.
//

import UIKit

extension UIView {
  /**
   * Places this view directly below `topView`
   */
  @discardableResult func placeBelow(_ topView: UIView,
                                     withMargin optMargin: CGFloat? = nil,
                                     x optX: CGFloat? = nil) -> UIView {
    let x = optX ?? self.frame.origin.x
    let y = topView.frame.maxY + (optMargin ?? 0)


    self.frame.origin = CGPoint(x: x, y: y)

    return self
  }

  func placeBelow(_ topView: UIView,
                  centeredTo centerToView: UIView,
                  withMargin optMargin: CGFloat? = nil) {
    let x = centerToView.frame.midX - (self.frame.width / 2)
    let y = topView.frame.maxY + (optMargin ?? 0)

    self.frame.origin = CGPoint(x: x, y: y)
  }

  @discardableResult func placeAbove(_ bottomView: UIView,
                                     withMargin optMargin: CGFloat? = nil,
                                     x optX: CGFloat? = nil) -> UIView {
    let x = optX ?? self.frame.origin.x
    let y = bottomView.frame.minY - self.frame.height - (optMargin ?? 0)

    self.frame.origin = CGPoint(x: x, y: y)

    return self
  }

  func placeAbove(_ bottomView: UIView,
                  centeredTo centerToView: UIView,
                  withMargin optMargin: CGFloat? = nil) {
    let centerX = centerToView.frame.midX - (self.frame.width / 2)
    let y = bottomView.frame.minY - self.frame.height - (optMargin ?? 0)

    self.frame.origin = CGPoint(x: centerX, y: y)
  }

  /**
   * Makes this view the same size as `sizeToView`
   */
  @discardableResult func resizeTo(_ sizeToView: UIView) -> UIView {
    var frame = self.frame
    frame.size.height = sizeToView.frame.height
    frame.size.width = sizeToView.frame.width

    self.frame = frame

    return self
  }

  /**
   * Centers the view on the x axis
   */
  @discardableResult func centerX(toView optView: UIView? = nil) -> UIView {
    // default to superview if no second view to center on is supplied
    let optView = optView ?? self.superview
    guard let view = optView else {
      print("No super view or other view to center on, cannot centerX for view")
      return self
    }

    self.center = CGPoint(x: view.frame.midX, y: self.frame.midY)

    return self
  }
}
Now my layout code looks as follows:
/**
 * Repositions views accordingly, without using constraints
 */
override func viewWillLayoutSubviews() {
  // point positioned label is static from the top,
  // if it wasn't I couldn't call it a point positioned view anymore :|
  self.pointPositionedLabel.frame.origin = CGPoint(x: 160, y: 70)

  // the framed label is basically tied to the nav bar
  // with a set x coordinate.
  self.framedLabel.placeBelow(self.navigationController!.navigationBar,
                              withMargin: 6,
                              x: 50)

  if UIApplication.shared.statusBarOrientation == .portrait {
  self.centerPositionedLabel.isHidden = false
  // the center positioned label goes below the framedLabel
  // if we're in landscape, that obfuscates the instructions label and can't touch this button
  // so if we are in landscape, don't show it
  self.centerPositionedLabel.placeAbove(self.instructionsLabel,
                                        centeredTo: self.view,
                                        withMargin: k.VIEW_MARGIN)
  }
  else {
    self.centerPositionedLabel.isHidden = true
  }

  // instructions label is center aligned
  self.instructionsLabel.center = self.view.center

  // can't touch this button goes below the instructions label.
  self.cantTouchThisButton.placeBelow(self.instructionsLabel,
                                      centeredTo: self.view,
                                      withMargin: k.VIEW_MARGIN)
}
Not perfect yet, but much better. I still have to go over the method naming and really hammer it out so that the method names make sense. I think there may be some ambiguity in saying withMargin: because it’s not always clear where the margin is.
I also implemented these originally to return a reference of self for fluent interface style method chaining. Which required the addition of the @discardableResult prefix to suppress Unused Result Warnings. This is something I may also want to drop all together. While it very convenient I’m not sure what performance impact changing the view’s frame repeatedly would have. Obviously people could still call the methods separtely if they wanted to, but I feel that having the method chaining would only encourage that behavior.

Locking Rotation, Altogether

If you want to lock out screen rotation completely you will need to override a get-only property of the UIViewController called shouldAutorotate, which returns a Bool:
open override var shouldAutorotate: Bool {
  return false
}
Now, if you’re using a UINavigationController, this won’t work on its own. You’ll need to extend UINavigationController to use whatever the current visible view controller says to do:
extension UINavigationController {
  open override var shouldAutorotate: Bool {
    return visibleViewController?.shouldAutorotate ?? true
  }
}
I set the default to true if there is no visible view controller because I am assuming allowing rotation is the default UINavigationController behavior.
If you wanted to apply this to all views across the entire app you could make the same extension to UIViewController. There’s also a way to do it through the plist file but since the topic is about how to move away from crazy Apple XML nonsense, I figure it’s cleaner and more obvious to have it in code.

评论

此博客中的热门博文

Resolving errSecInternalComponent errors during code signing

原文链接 One code signing issue I commonly see, both here on DevForums and in my Day Job™ with DTS, is that the codesign command fails with errSecInternalComponent. This issue crops up in a wide variety of circumstances and the correct fix depends on the specific problem. This post is my attempt to clarify the potential causes of this error and help folks resolve it. If you have any questions or comments about this, please start a new thread, tagging it with Code Signing so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Resolving errSecInternalComponent errors during code signing In some circumstances the codesign command might fail with the error errSecInternalComponent. For example: % codesign -s "Apple Development" "MyTrue" MyTrue: errSecInternalComponent This typically affects folks who are signing code in a nonstandard environm...

iOS:检测使用VPN或Proxy

参考链接: https://www.jianshu.com/p/c3b950dbf86a https://gist.github.com/PramodJoshi/4faad4c91f7dcb4eb9b06be8390c01db http://noodlecode.net/2018/04/check-if-ios-app-is-connected-to-vpn 第一种方法 需要导入框架CFNetwork 然后,这个方法是mrc的:需要添加-fno-objc-arc的flag 代码如下: + ( BOOL )getProxyStatus { NSDictionary *proxySettings = NSMakeCollectable ([( NSDictionary *) CFNetworkCopySystemProxySettings () autorelease]); NSArray *proxies = NSMakeCollectable ([( NSArray *) CFNetworkCopyProxiesForURL (( CFURLRef )[ NSURL URLWithString: @"http://www.google.com" ], ( CFDictionaryRef )proxySettings) autorelease]); NSDictionary *settings = [proxies objectAtIndex: 0 ]; NSLog ( @"host=%@" , [settings objectForKey:( NSString *)kCFProxyHostNameKey]); NSLog ( @"port=%@" , [settings objectForKey:( NSString *)kCFProxyPortNumberKey]); NSLog ( @"type=%@" , [settings objectForKey:( NSString *)kCFProxyTypeKey]); if ([[settings object...

去广告DNS设置,国内ADGuard DNS方案,手机电脑iOS去广告,保护隐私

 原文链接 之前分享过使用mac系统搭建adguard home,这几个月用下来零零散散基本上也被弃用了。主要原因是因为需要保持电脑一直开机。但是我的电脑是笔记本,存在移动各个地域的情况,也就是说只能够屏蔽电脑自身,对于手机而言不太现实。今天偶然发现dnspod推出了高级版的公共解析。dnspod背靠腾讯云,肯定是合法合规的公共解析服务,这个高级版用起来不错。 国内自己搭建解析服务是违法行为,所以这也是为什么使用dnspod的原因。 后台截图 开始使用 首先我们先进入dnspod的公共解析页面,点击开始使用。 专业版公共解析 dnspod会提供几种预设,我们选择「开发者」即可 开发者 然后你就成功的申请到自己个人使用的dns了! 更新拦截规则 我们可以将常见的广告过滤规则加入到dns中。我们在顶部选项卡中选择「拦截规则」。 拦截规则设置 打开adguard adguard 绑定iOS设备 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 绑定macOS 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 mac需要在「系统偏好设置」的「网络」中查看是否正在运行。 代理 如果没有运行需要点击「···」来启动服务。 启动服务 绑定路由器 找到自己路由器的DHCP设置,修改dns,然后记得绑定自己的ip。 修改dns 绑定ip 费用 目前有300万次/月的免费额度,但没有超出之后的价格。300万次一个人比较难用完,可以放心使用。 我个人使用iOS设备两台、智能家居、电脑两台,日均请求数大致2万/日。 判断是否搭建成功 可以通过查看日志的方式,日志大概有半小时到一小时的延迟,请耐心等待。