如何将两个按钮对齐到UIToolbar的左右边界

4

我一直在尝试使用Cocoa和Swift进行实验(我是新手),但遇到了一个问题,似乎无法解决:

假设我创建了一个UIToolbar并向其中添加了两个按钮:“取消”和“接受”。我想将取消按钮与UIToolbar的左边缘对齐(默认情况下可以实现),将接受按钮与右边缘对齐。有没有什么简单的方法来实现右对齐?目前我的代码如下:

let toolbar = UIToolbar(frame: CGRectMake(0, 0, w, 35))
toolbar.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 0.95)
let acceptButton = UIBarButtonItem(title: "Accept", style: UIBarButtonItemStyle.Done, target: self, action: "buttonPressed:")
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "buttonPressed:")
let space = UIBarButtonItem(customView: UIView(frame: CGRectMake(0, 0, 50, 10))) // <- MEH! this is not dynamic!
toolbar.items = [acceptButton, space, cancelButton]
view.addSubview(toolbar)

我正在使用另一个UIBarButtonItem来创建空格,但这不是动态的(许多在SO上的答案建议使用此解决方案-不好)。所以我期望能够获得UIBarButtonItems的框架,但我似乎也无法使其工作,它们没有.frame属性。因此,在另一个SO答案中提出了以下建议:

UIView *view= (UIView *)[self.toolbar.subviews objectAtIndex:0]; // 0 for the first item

这也不起作用,似乎没有直接的子视图是UIBarButtonItem(因此它返回的宽度为375)。

设置标签也行不通...:

let cancelButton.tag = 1
let acceptButton.tag = 0
let acceptButtonFrame = toolbar.viewWithTag(0)!.frame
let cancelButtonFrame = toolbar.viewWithTag(1)!.frame
println(acceptButtonFrame.width)
println(cancelButtonFrame.width)

产生于:

375.0

致命错误:在强制解包可选值时意外发现nil

(lldb)

有什么方法吗?:-/ 感谢任何帮助。

2个回答

9
是的,只需在它们之间添加一个灵活的空间即可。
let toolbar = UIToolbar(frame: CGRectMake(0, 0, w, 35))
toolbar.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 0.95)
let acceptButton = UIBarButtonItem(title: "Accept", style: UIBarButtonItemStyle.Done, target: self, action: "buttonPressed:")
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "buttonPressed:")
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil);
toolbar.items = [acceptButton, flexibleSpace, cancelButton]

我不确定那是否是正确的语法,但类仍然是UIBarButtonItem。唯一的区别是systemItem为UIBarButtonSytemItem.FlexibleSpace

评论:

So in another SO answer this was the suggestion:

UIView *view= (UIView *)[self.toolbar.subviews objectAtIndex:0]; // 0 for the first item

This doesn't work either, seems like no direct subview-child is a UIBarButtonItem (and so it returns the width as 375).

这个代码无法正常工作的原因是因为[self.toolbar.subviews objectAtIndex:0]是Objective-C代码,而不是Swift代码。


我该如何使用代码在它们之间添加一个灵活的空间?这是哪个类?或者我如何使那个按钮具有灵活性? - Fygo
就是这样!非常感谢。 - Fygo
对评论的回复:当然我知道,我已经将它翻译成了Swift :) 工具栏显示了4个子项,但是它们都没有起作用。所有这些子项都被追踪为“is UIBarButtonItem”(或者幕后进行了某种转换?),并且宽度不正确。 - Fygo

3

您需要使用FlexibleSpace buttonSystem作为分隔符。

let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace,
              target: nil,
              action: nil);

这将自动缩放。
祝好,

谢谢,我猜你比被接受的答案得到“纠正”更早回答了,我至少会点赞你的回答。 - Fygo
1
呵呵..谢谢,重要的是你已经修好了你的代码 :) - Florian Burel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接