如何删除/替换Swift中UITabbarController子类中的tabBar项?

时间:2015-03-11 17:43:25

标签: ios swift uitabbarcontroller uitabbar

我不知道为什么我在这一行上收到错误thread 1 breakpoint 1.1

self.tabBar.setItems(items, animated: false)

我尝试用自定义按钮替换标签栏中的当前项目。

以下是代码:

class MyTabController : UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let button1 = UIButton(frame: CGRectMake(0, 0, self.view.frame.width*0.3, self.view.frame.height))
        button1.addTarget(self, action: "button1Clic", forControlEvents: UIControlEvents.TouchUpInside)
        button1.backgroundColor = UIColor.orangeColor()

        /*
        let items = NSMutableArray(array: self.tabBar.items!)
        items.removeObjectAtIndex(0)
        */
        let array = [button1]
        let items = NSMutableArray(array: array)
        self.tabBar.setItems(items, animated: false) //HERE

        /*
        //in objective-c
        NSMutableArray *items = [NSMutableArray arrayWithArray:self.tabBar.items];
        [items removeObjectAtIndex:0];
        [self.tabBar setItems:items];
        */

        self.tabBar.addSubview(button1)
    }

    func button1Clic() {
        println("1 clic")
    }
}

编辑:
这不起作用,我得到了与以前相同的错误:

let tab1 = UITabBarItem(title: "test", image: UIImage(named:"food3.png"), tag: 0)
self.tabBar.setItems([tab1], animated: false)

关于按钮,它们被正确添加到tabBar,但它被放在其他项目的上方?有没有办法用按钮替换uitabbarItem?

由于

1 个答案:

答案 0 :(得分:0)

问题是您使用UIButton数组调用self.tabBar.setItems。它应该使用UITabBarItem数组调用。

let barItem = UITabBarItem(tabBarSystemItem: .Featured, tag: 0)
self.tabBar.setItems([barItem], animated: false)

如果你想在标签栏上使用UIButton,只需在你写的时候调用addSubview:

let button1 = UIButton(frame: CGRectMake(0, 0, self.view.frame.width*0.3, self.view.frame.height))
button1.addTarget(self, action: "button1Clic", forControlEvents: UIControlEvents.TouchUpInside)
button1.backgroundColor = UIColor.orangeColor()
self.tabBar.addSubview(button1)