Swift-leftBarButtonItems的Love And Hate

前端之家收集整理的这篇文章主要介绍了Swift-leftBarButtonItems的Love And Hate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天写swift的时候碰到一个问题,添加一个navigationController,然后在左边连续放3个view。具体oc的代码是这样的。

- (void)createNavBar{
    //1. logo
    UIBarButtonItem *logo = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"logo"] style:UIBarButtonItemStyleDone target:nil action:nil];
    //2. 3个UIbarButtonItem
    NavItem *first = [NavItem makeItem];
    [first addtarget:self action:@selector(firstClick)];
    NavItem *second = [NavItem makeItem];
    [second addtarget:self action:@selector(secondClick)];
    NavItem *third = [NavItem makeItem];
    [third addtarget:self action:@selector(thirdClick)];

    firstItem= [[UIBarButtonItem alloc]initWithCustomView:first];
    secondItem = [[UIBarButtonItem alloc]initWithCustomView:second];
    thirdItem = [[UIBarButtonItem alloc]initWithCustomView:third];
    self.navigationItem.leftBarButtonItems = @[logo,firstItem,secondItem,thirdItem];
}

代码意思很明朗,就是在左边创建了3个barbuttonItem,效果如下,完美实现:

接下来我用swift代码写:

let left =  NaviBarItem.initXib();
        let fistItem = UIBarButtonItem(customView: left)
        let secondItem = UIBarButtonItem(customView: left)
        let thirdItem = UIBarButtonItem(customView: left)
        self.navigationItem.leftBarButtonItems = [fistItem,thirdItem]

按照道理,这是没有问题的,swift和oc用的是同一套API啊。测试,问题就来了。

貌似这三个view 都重叠在一起了。这个谁也没有办法预料这是什么情况。开发苹果突然觉得有点局限性,因为苹果不开源,我不知道方法的具体实现。因此不知道从哪儿入手去解决,只好凭着猜测去一个个测试。

所以我就这样写了:

let left =  NaviBarItem.initXib();
        var arr:NSMutableArray = []
        for index in 1...3{
            let width = left.frame.size.width
            let height = left.frame.size.width

            let leftItem = NaviBarItem.initXib()
            let w:CGFloat = CGFloat(index) * width
            leftItem.frame = CGRectMake(w,height,120,40)
            var item = UIBarButtonItem(customView: leftItem)
            arr.addObject(item)
        }
        self.navigationItem.leftBarButtonItems = arr as [AnyObject]

设置3个view的坐标。测试结果:
基本上一样,可是为什么会发生这样的现象?真的很疑惑啊,如果有大神知道的话,请留个言告诉我一下。

猜你在找的Swift相关文章