自定义后退指示图像和iOS 11

时间:2017-09-13 09:01:32

标签: ios ios11

我在我的应用中使用自定义后退按钮。此自定义后退按钮全局设置如下:

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back").withRenderingMode(.alwaysOriginal)
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(asset: .back).withRenderingMode(.alwaysOriginal)

在iOS 11之前,这段代码可以解决问题,但是现在在iOS 11中按钮不再垂直居中,如您所见:

enter image description here

我可以将后退按钮图像的高度更改为44,但这会在iOS< 11.我也可以使用两个不同的图像,但我正在寻找更清洁的东西,比如在后面按钮容器视图中垂直居中图像的方法。

修改

事实证明,正如banxii1988所说,问题是由setBackButtonTitlePositionAdjustment引起的,当值故意将标题移到可见屏幕之外时。这是一个黑客,以避免删除每个视图控制器中的后退按钮标题。我决定删除这个黑客​​,我做了正确的事情:

  1. 将故事板中的后退按钮项设置为" "
  2. 在没有相关故事板的每个视图控制器中,我设置 以编程方式backBarButtonItem navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
  3. 请注意,您在视图控制器中看到的后退按钮标题是在导航堆栈中的上一个中设置的。

9 个答案:

答案 0 :(得分:12)

我认为这种方法还可以!这对我很有用。

Dim conn As ADODB.Connection

On Error GoTo ErrorHandler
Set conn = CurrentProject.Connection

With conn

    .BeginTrans

     'insert a new customer record
    .Execute "INSERT INTO ContactDetails (" & _
             "FirstName, " & _
             "LastName , " & _
             "TelNo , " & _
             "MobileNo ," & _
             "EmailAddress ," & _
             "IsPrimaryContact) " & _
             "Values ( " & _
             "'" & Me.FirstName & "'," & _
             "'" & Me.LastName & "'," & _
             "'" & Me.TeleNum & "'," & _
             "'" & Me.MobileNum & "'," & _
             "'" & Me.EmailAddress & "'," & _
             False & ");", , adCmdText + adExecuteNoRecords

            'Added from a possible solution
            Dim rs As New ADODB.Recordset
            Set rs = conn.Execute("SELECT @@Identity", , adCmdText)
            Debug.Print rs.Fields(0).Value  ' This returned 0

        'Inset a new record into the ReportingType Table
        For i = 1 To ListView1.ListItems.Count
            If ListView1.ListItems(i).Checked Then
                 .Execute "INSERT INTO ReportingType " & _
                          "(ReportType,  ContactID) " & _
                          "VALUES " & _
                          "('" & colReportType(ListView1.ListItems(i)) & "' , " & ContactID & ")"
            End If

        Next i

    .CommitTrans
End With
ExitHere:
    Set conn = Nothing
    Exit Sub
ErrorHandler:
    If Err.Number = -2147467259 Then
        MsgBox Err.Description
        Resume ExitHere
    Else
        MsgBox Err.Description
        With conn
            .RollbackTrans
            '.Close
        End With
        Resume ExitHere
    End If
End Sub

答案 1 :(得分:12)

对于任何无法解决问题的人:

1)在您的项目中搜索(cmd + shift + f)" setBackButtonTitle",您将找到如下代码:

[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[xController class]]] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

2)用以下代码更改上面的代码:

[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[xController class]]] setBackButtonTitlePositionAdjustment:UIOffsetMake(-200, 0) forBarMetrics:UIBarMetricsDefault];

从iOS 11开始,上面的代码我们用来隐藏按钮标题,后退按钮和标题本身。但是,如果只是水平移动后退按钮标题,一切正常,并且没有后退。

答案 2 :(得分:10)

1)删除PositionAdjustment(如果有)。比如

  bap.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -64), for: .default)

2)检查导航堆栈中的前一个ViewController是否具有标题

答案 3 :(得分:4)

此解决方案适用于iOS 9,10和11

<div class="bg-faded p-4 my-4">
  <hr class="divider">
  <h2 class="text-center text-lg text-uppercase my-0"><strong>Notícias</strong></h2>
  <hr class="divider">
  <div class="bg-faded p-4 my-4">
    <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
      <div class="carousel-inner" role="listbox">
        <div class="carousel-item active">
          <img class="img-fluid float-left mr-4 d-none d-lg-block" src="img/noticia1.jpg" alt="" style="max-width: 250px; max-height: 150px;">
          <p>A Fidelidade brilhou na Web Summit 2017 com o programa Protechting by Fosun & Fidelidade e atraiu cerca de 180 novas candidaturas de startups! Um número promissor que confirma o prestígio associado a esta iniciativa, bem como o nosso compromisso com o empreendedorismo, a inovação tecnológica e o desenvolvimento do País. Obrigado a todos que estiveram connosco nestes dias!</p>
        </div>
        <div class="carousel-item">
          <img class="img-fluid float-left mr-4 d-none d-lg-block" src="img/noticia2.png" alt="" style="max-width: 250px; max-height: 150px;">
          <p>Agora já não precisa de sair de casa para ir ao médico. Vá por telefone ou vídeo.</p>
        </div>
      </div>
    </div>
  </div>
</div>

答案 4 :(得分:3)

经过多次尝试并失败后,这适用于iOS 11:

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-200, -5) forBarMetrics:UIBarMetricsDefault];

诀窍是移动&#34; Back&#34; x轴上的文字很多,y轴上的一点,因为setBackButtonTitlePositionAdjustment结果影响了图像和文本。

但是,我们不知道这个解决方案能运行多长时间,它可能会被修复&#34; Apple随时都可以

答案 5 :(得分:1)

我建议使用方法调配来解决它,我已经在我的一些项目中使用了这个解决方案,并且工作正常。

1 - 创建一个UIViewController类别。

2-导入#import <objc/runtime.h>

3-粘贴以下方法

#import "UIViewController+Extras.h"
#import <objc/runtime.h>
@implementation UIViewController (Extras)

+ (void)load {
    static dispatch_once_t once_token;
    dispatch_once(&once_token,  ^{
        SEL viewDidLoadSelector = @selector(viewDidLoad);
        SEL viewDidLoadModifyBackButtonSelector = @selector(modifyBackButton_viewDidLoad);
        Method originalMethod = class_getInstanceMethod(self, viewDidLoadSelector);
        Method extendedMethod = class_getInstanceMethod(self, viewDidLoadModifyBackButtonSelector);
        method_exchangeImplementations(originalMethod, extendedMethod);
    });
}

- (void)modifyBackButton_viewDidLoad {
    [self modifyBackButton_viewDidLoad];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:self.navigationItem.backBarButtonItem.style target:nil action:nil];
}

@end

答案 6 :(得分:1)

if(@available(iOS 11, *)) {
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];

} else {
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60) forBarMetrics:UIBarMetricsDefault];
}

@Tonin的上述解决方案有效,但唯一的问题是导航栏左键文本(如&#34;取消&#34;)与其他应用程序共享时的透明(清晰颜色)(电子邮件,消息等) ,翻转颜色,如果需要共享功能:

UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[title, URL] applicationActivities:nil];
[activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
     // set clear color when back from share
     [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
}];
[self presentViewController:activityViewController animated:YES completion:^{
     // set white color when share to other app 
     [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal];
}];

答案 7 :(得分:0)

FOR SWIFT 3 +

     if #available(iOS 11, *) {
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
     } else {
            UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0,
-60), for:UIBarMetrics.default)
        }

答案 8 :(得分:0)

1。

extension UINavigationController {
    func pushViewC(_ viewController: UIViewController, animated: Bool) {
        viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "return").withRenderingMode(.alwaysOriginal), style: .plain, target: navigationController, action: #selector(popViewController(animated:)))
        pushViewController(viewController, animated: animated)
    }
}

2。使用pushViewC代替pushViewController

navigationController?.pushViewC(otherVC, animated: true)