我创建了一个 UIAlertController
,其首选样式为 UIAlertControllerStyleAlert
。当点击 leftBarButtonItem
时会显示警报。我创建了一个名为 backButton
的 UIBarButtonItem
属性并设置了 leftBarButtonItem = self.backButton
。这是按设计工作的。我没有使用 Storyboard。
问题是当显示警报时 leftBarButtonItem
向下移动(我猜:大约 20pts)。为什么会这样?
我知道如何显示/隐藏按钮,以便用户在按钮向下移动时看不到该按钮。然而,这很糟糕。为什么会发生这种情况?
我还没有在网上找到任何类似的问题。
@property (strong, nonatomic) IBOutlet UIBarButtonItem *backButton;
在viewDidLoad中:
self.backButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed)];
[self.backButton setImage:[UIImage imageNamed:@"back-arrow-grey"]];
self.navigationItem.leftBarButtonItem = self.backButton;
在backButtonPressed中:
{
self.navigationItem.leftBarButtonItem = nil; //to hide backButton because it moves down
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"My title" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionLeave = [UIAlertAction actionWithTitle:@"Leave" style:UIAlertActionStyleDefault handler:...//which works correctly
UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"Go back" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
self.navigationItem.leftBarButtonItem = self.backButton; //to show backButton again now that the alert is dismissed
//other things happen here that work as designed
}];
[alertController addAction:actionLeave];
[alertController addAction:actionCancel];
[self presentViewController:alertController animated:YES completion:^{}];
}
最佳答案
我也遇到了这个问题。搜索有关左侧栏按钮项目垂直定位错误的其他问题将我带到了 this question .它的要点是,由于未知原因,如果您有一个带有图像的条形按钮项目,但标题为空字符串,则会出现此问题。将标题设置为单个空格而不是空字符串:
self.backButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed)];
我不知道它是否会为你修复它,但它主要对我有用 - 按钮仍然会做一个轻微的“跳跃”动画,就好像它是新创建的(但只是第一次出现) - 但是它保持在相同的垂直位置。
编辑:将 nil 作为标题传递也会删除无关的动画。似乎这只是 iOS 将空白字符串作为标题处理的一个特点。
关于objective-c - UIAlertController 将 leftBarButtonItem 向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748538/