Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UINavigationBar中的对中UIButton不工作_Ios_Objective C - Fatal编程技术网

Ios UINavigationBar中的对中UIButton不工作

Ios UINavigationBar中的对中UIButton不工作,ios,objective-c,Ios,Objective C,_导航栏中的UIButton不居中 //Create UIButton UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [closeButton setTitle:@"Close" forState:UIControlStateNormal]; //Create Navigation Item UINavigationItem *navigationItem = [[UINavigationIt

_导航栏中的UIButton不居中

//Create UIButton
UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[closeButton setTitle:@"Close" forState:UIControlStateNormal];
//Create Navigation Item
UINavigationItem *navigationItem = [[UINavigationItem alloc]init]; 
CGRect screenRect = [[UIScreen mainScreen] bounds]; 
CGPoint center = CGPointMake(screenRect.size.width/2, 0.0f);
//Center titleView of Navigation Item and add closeButton
[navigationItem.titleView setCenter:center];
[navigationItem setTitleView:closeButton];
[_navigationBar setItems:@[navigationItem]];
它显示为始终与右侧对齐:

任何帮助都将不胜感激。谢谢

默认情况下,UINavigationItem的标题视图已居中。我认为你代码中的设置中心是导致问题的原因。试试这个:

UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[closeButton setTitle:@"Close" forState:UIControlStateNormal];
//Create Navigation Item
UINavigationItem *navigationItem = [[UINavigationItem alloc]init]; 

[navigationItem setTitleView:closeButton];

[_navigationBar setItems:@[navigationItem]];
编辑:视图控制器应该已经有一个导航项供您修改。试试这个代码

UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [closeButton setTitle:@"Close" forState:UIControlStateNormal];

self.navigationItem.titleView = closeButton;

我认为你没有正确访问你的导航栏。如果这是UIViewController,您应该已经有了要修改的navigationItem。请看我的编辑。我刚刚试过这个,效果非常好。。。所以这应该行得通。我将UINavigationBar拖到ViewController上,并且_navigationBar与之相连。我尝试了你的方法,但我认为我的UIViewController没有navigationItem,因为navigationBar是空的。哎呀,我没有意识到你必须固定UINavigationBar。谢谢你的帮助。我是个白痴