天天看點

(0027)iOS 開發之調整導覽列上BarButtonItem與螢幕邊界的間距

       我們發現,在設定navigationItem的leftBarButtonItem或rightBarButtonItem時,用CustomView初始化UIBarButtonItem,不論怎麼設定CustomView的frame,添加到導覽列上之後總是和螢幕邊界有一定的間距(5pix),如何自由調整這個間距呢?

初始化一個用于控制間距的UIBarButtonItem執行個體negativeSpacer,并設定negativeSpacer的width屬性的值,設為-5的時候,正好可以使按鈕與螢幕邊界值為0,以rightBarButtonItem情況為例 

        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];

        _rightBtn.frame = CGRectMake(0, 0,60, 40);

        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];

        [_rightBtn setTitleColor:hexColor(808080) forState:UIControlStateNormal];

        [_rightBtn setTitle:@"全部已讀" forState:UIControlStateNormal];

        [_rightBtn addTarget:self action:@selector(clearAllUnreadMessage) forControlEvents:UIControlEventTouchUpInside];

        UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBtn];

        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

// width為負數時,相當于btn向右移動width數值個像素,由于按鈕本身和邊界間距為5pix,是以width設為-5時,間距正好調整 

// 為0;width為正數時,正好相反,相當于往左移動width數值個像素  

       negativeSpacer.width = -10;

       self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, rightBarItem, nil];

繼續閱讀