【问题标题】:How to put a button in middle of the UIView Horizontally and Vertically for any device?如何在任何设备的 UIView 中间水平和垂直放置一个按钮?
【发布时间】:2013-04-11 18:17:23
【问题描述】:

我有一个 UIButtonRoundedRectType 类型的 UIButton,我想将它水平和垂直放在屏幕中间。

我尝试通过对数字进行硬编码来做到这一点,但是当在 iPhone 与 iphone(视网膜)上运行时,这会回头看。我想通过计算容器的宽度以编程方式将按钮保持在中心。

所以,我已经尝试过了,但它不起作用。

container = view.frame.size
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button.frame = [[container.width/2-button.frame.size.width/2,150], [280,50]]

【问题讨论】:

  • 您可以使用 Storyboards 和布局约束来做到这一点。这样你就不必担心硬编码任何东西。 raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
  • 什么不起作用?你用什么来“查看”?
  • (请记住,以上内容只会在“view”内居中。如果“view”未居中,则按钮将同样偏离中心。)
  • 视图是一个 UIViewController

标签: iphone objective-c rubymotion


【解决方案1】:

简单的方法:

button.center = view.center;

【讨论】:

    【解决方案2】:

    怎么样:

    button.center = [button.superview convertPoint:button.superview.center fromView:button.superview.superview];
    

    【讨论】:

      【解决方案3】:

      你离得不远了。这行得通(我试过了):

      container = view.frame.size
      button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
      button_size = [ 280, 50 ]
      left_margin = (container.width / 2) - (button_size[0] / 2)
      top_margin = (container.height / 2) - (button_size[1] / 2)
      button.frame = [[ left_margin, top_margin ], button_size ]
      button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin
      

      【讨论】:

        【解决方案4】:

        如果你在 XIB 中使用视图,你可以像我提到的那样使用。

        转到 XIB -> 点击查看 -> 点击尺寸检查器 -> 排列(您可以在此处设置位置)。

        选择Position of ContainerFill Container的所有属性。

        如果你动态创建视图(不在 XIB 中),那么你可以根据 superview 的边界使用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2011-06-20
          • 2016-08-15
          • 1970-01-01
          • 2017-09-23
          • 1970-01-01
          • 2010-11-20
          相关资源
          最近更新 更多