6

在我的应用程序中,我在界面构建器中设计了一个视图。
这个视图有一个工具栏,里面有一些 UIBarButtonItem。

我的按钮可以是自定义图像,也可以是默认按钮,如分享、添加、...
现在在 iOS7 中,按钮不再有边框。所以我想补充一些。 在此处输入图像描述

这是我想做的:在我的屏幕截图上添加像白线这样的边框。我尝试的是在工具栏上添加一个 UIButton 。在我的示例中,我设置了后退按钮大小 (12x44)。我将此按钮添加为视图控制器的 IBOutlet 属性,并尝试为其绘制边框:

CALayer *cancelBorder = [CALayer layer];
[cancelBorder setFrame:CGRectMake(12, 0, 1, 44)];
[backBorder setBackgroundColor:[[UIColor whiteColor] CGColor]];
[backButton.layer addSublayer:cancelBorder];

但它不起作用。有人有解决方案吗?

4

2 回答 2

10

以编程方式将 UIBarButtonItem 添加到工具栏可能会解决您的问题。

首先,创建带有图像、边框等的自定义按钮。正如 HereTrix 所说,您可以为该按钮添加边框。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 0, 30, 30);
button.layer.borderColor = [UIColor blueColor].CGColor;
button.layer.borderWidth = 1.0f;
/* any other button customization */

然后,使用该自定义按钮初始化 UIBarButtonItem 并将此项添加到您的工具栏。

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.toolBar.items = @[backButton];
于 2013-09-26T18:13:02.737 回答
8

Swift 3:下面是我对按钮自定义和事件处理的完整实现。

测试 UIBarButtonItem

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton.init(type: .custom)
    button.setTitle("Tester", for: .normal)
    button.setTitleColor(.darkGray, for: .normal)
    button.layer.borderWidth = 1
    button.layer.cornerRadius = 5
    button.layer.borderColor = UIColor.darkGray.cgColor
    button.addTarget(self, action: #selector(self.handleButton), for: .touchUpInside)

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let button = self.navigationItem.rightBarButtonItem?.customView {
        button.frame = CGRect(x:0, y:0, width:80, height:34)
    }
}

func handleButton( sender : UIButton ) {
    // It would be nice is isEnabled worked...
    sender.alpha = sender.alpha == 1.0 ? 0.5 : 1.0
}

希望这可以帮助

于 2017-02-02T19:15:16.587 回答