【问题标题】:Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar在 UIToolbar 上创建左箭头按钮(如 UINavigationBar 的“后退”样式)
【发布时间】:2010-09-18 15:08:26
【问题描述】:

我想在UIToolbar 中创建一个“后退”左箭头边框按钮。

据我所知,获得其中之一的唯一方法是将UINavigationController 保留为默认设置,并将其用于左侧栏项目。但是我无法找到将其创建为UIBarButtonItem,因此我无法在标准UIToolbar 中创建一个,即使它们与UINavigationBars 非常相似。

我可以使用按钮图像手动创建它,但我无法在任何地方找到源图像。它们具有 alpha 通道边缘,因此截屏和剪切不会得到非常通用的结果。

对于我打算使用的每种尺寸和配色方案,除了截图之外还有什么想法吗?

更新:请停止回避这个问题并暗示我不应该问这个,应该使用UINavigationBar。我的应用是 Instapaper Pro。它只显示一个底部工具栏(以节省空间和最大化可读内容区域),我希望在底部放置一个左箭头形的返回按钮。

告诉我我不应该这样做不是答案,当然也不值得赏金。

【问题讨论】:

标签: ios iphone cocoa-touch uinavigationbar uitoolbar


【解决方案1】:

好吧,您不必为每种尺寸设置不同的按钮,您可以使用[UIImage stretchableImageWithLeftCapWidth:topCapHeight:],但我发现的唯一内容是自定义图像。

【讨论】:

    【解决方案2】:

    你为什么要这样做?如果您想要看起来像导航栏的东西,请使用 UINavigationBar。

    工具栏具有与之相关的特定视觉风格。 iPhone 状态的人机界面指南:

    一个工具栏出现在屏幕的底部边缘,其中包含执行与当前视图中的对象相关的操作的按钮。

    然后它给出了几个没有文字的大致方形图标的视觉示例。我会敦促你在这方面关注 HIG。

    【讨论】:

    • 我知道了,谢谢。但是,我相信我的预期用途是合适的。假设我真的想做我所问的事情,你能提供更多帮助吗?
    • 如果你把它放在屏幕的顶部,那就是用错了。比较 UINavigationBar 和 UIToolbar 之间的渐变和边框,您会发现它们略有不同。你肯定想在屏幕顶部使用 UINavigationBar。
    • 我把它放在底部了。
    【解决方案3】:

    我使用了以下来自http://www.teehanlax.com/blog/?p=447的psd

    http://www.chrisandtennille.com/pictures/backbutton.psd

    然后我创建了一个自定义 UIView,我在工具栏项的 customView 属性中使用它。

    很适合我。


    编辑:As pointed out by PrairieHippomaralbjo 发现使用以下简单代码可以解决问题(需要捆绑包中的自定义图像)应该与此答案结合使用。所以这里是附加代码:

    // Creates a back button instead of default behaviour (displaying title of previous screen)
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(backAction)];
    
    tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
    [backButton release];
    

    【讨论】:

    • 我上传的 PSD 是一个黑色的工具栏。我没有尝试太多蓝色的,因为我的应用程序没有使用它。但据我所知,工具栏不会根据需要重新着色。克里斯。
    • 您不需要任何特殊工具来重新着色,我已经使用 Mac Preview 的“调整颜色”选项完成了。
    • 这个解决方案能详细说明一下吗?
    • 这个psd只对1.0f的屏幕比例有用。在视网膜显示器上它看起来很糟糕。
    • 不要为此使用图像,只要正确使用即可(请参阅stackoverflow.com/questions/4260238 的答案)。
    【解决方案4】:

    如果您想避免自己绘制,可以使用未记录的类:UINavigationButton,样式为 1。当然,这可能会阻止您的应用程序获得批准... /约翰

    【讨论】:

      【解决方案5】:

      您可以通过从 UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork 中的 Other.artwork 中提取它们来找到源图像。改装社区有一些提取它们的工具,here。提取图像后,您可以编写一些代码以根据需要对其重新着色并将其设置为按钮图像。您是否真的可以运送这样的东西(因为您要嵌入派生的艺术品)可能有点冒险,所以也许您想和律师谈谈。

      【讨论】:

        【解决方案6】:

        我不确定这是否可行,但您可以尝试使用默认设置创建一个 UINavigationController 来创建按钮,在导航控制器的子视图层次结构中找到该按钮,在其上调用 removeFromSuperview,销毁导航控制器,然后将按钮添加为工具栏的子视图。在调用removeFromSuperview 之前,您可能还需要retain 和按钮(然后在将其添加为工具栏的子视图后release)以避免在此过程中释放它。

        【讨论】:

          【解决方案7】:

          要为 UIToolbar 创建一个图像,请在 photoshop 中制作一个 png,然后在有任何颜色的地方将其设为白色,并且在 alpha = 0 的地方将其置之不理。

          SDK 实际上会在您创建的图标周围放置边框并将其变为白色,而您无需执行任何操作。

          看,这是我在 Photoshop 中为前进按钮制作的(显然将其换成后退按钮):

          http://twitpic.com/1oanv

          这就是它在 Interface Builder 中的样子

          http://twitpic.com/1oaoa

          【讨论】:

            【解决方案8】:

            Three20 库有办法做到这一点:

              UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @"Title" style:UIBarButtonItemStylePlain 
                                                                            target:self action:@selector(foo)];
            
              UIColor* darkBlue = RGBCOLOR(109, 132, 162);
            
              TTShapeStyle* style = [TTShapeStyle styleWithShape:[TTRoundedLeftArrowShape shapeWithRadius:4.5] next:
                [TTShadowStyle styleWithColor:RGBCOLOR(255,255,255) blur:1 offset:CGSizeMake(0, 1) next:
                [TTReflectiveFillStyle styleWithColor:darkBlue next:
                [TTBevelBorderStyle styleWithHighlight:[darkBlue shadow]
                                                 shadow:[darkBlue multiplyHue:1 saturation:0.5 value:0.5]
                                                  width:1 lightSource:270 next:
                [TTInsetStyle styleWithInset:UIEdgeInsetsMake(0, -1, 0, -1) next:
                [TTBevelBorderStyle styleWithHighlight:nil shadow:RGBACOLOR(0,0,0,0.15)
                                                    width:1 lightSource:270 next:nil]]]]]];
            
              TTView* view = [[[TTView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)] autorelease];
              view.backgroundColor = [UIColor clearColor];
              view.style = style;
              backButton.customView = view;
            
            
              self.navigationItem.leftBarButtonItem = backButton;
            

            【讨论】:

            • 能否发一张最终结果的截图?
            • 看起来很糟糕。从来没有让左箭头后退按钮看起来很正确。我放弃了,并在 Three20 导航器上使用了适当的后退按钮。
            【解决方案9】:

            Unicode 方法

            我认为只使用 unicode 字符来完成工作要容易得多。您可以通过谷歌搜索Unicode TrianglesUnicode Arrows 来查看箭头。从 iOS6 开始,Apple 将字符更改为带边框的 emoji 字符。要禁用边框,我添加了 0xFE0E Unicode Variation Selector

            NSString *backArrowString = @"\U000025C0\U0000FE0E"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR
            
            UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:nil action:nil];
            self.navigationItem.leftButtonItem = backBarButtonItem;
            

            代码块仅用于演示。它适用于任何接受 NSString 的按钮。

            要获取完整的字符列表,请在 Google 中搜索 Unicode 字符和您想要的字符。这是Black Left-Pointing Triangle 的条目。

            结果

            【讨论】:

              【解决方案10】:

              警告:有报道称这不适用于 iOS 6。这可能仅适用于旧版本的操作系统。显然,至少有一个开发者因为使用了这个技巧而拒绝了他们的应用程序(参见 cmets)。使用风险自负。使用图片(参见上面的答案)可能是更安全的解决方案。

              这可以在不添加您自己的图像文件的情况下使用 sekr1t 按钮类型 101 来完成,以获得正确的形状。对我来说,诀窍是弄清楚我可以使用initWithCustomView 来创建BarButtonItem。我个人需要将它用于动态导航栏而不是 toolbar,但我使用工具栏对其进行了测试,代码几乎相同:

              // create button
              UIButton* backButton = [UIButton buttonWithType:101]; // left-pointing shape!
              [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
              [backButton setTitle:@"Back" forState:UIControlStateNormal];
              
              // create button item -- possible because UIButton subclasses UIView!
              UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
              
              // add to toolbar, or to a navbar (you should only have one of these!)
              [toolbar setItems:[NSArray arrayWithObject:backItem]];
              navItem.leftBarButtonItem = backItem;
              

              如果您在工具栏上执行此操作,则必须调整设置项目的方式,但这取决于您的代码的其余部分,我将其作为练习留给读者。 :P 这个示例对我有用(编译并运行)。

              等等,阅读 HIG,不要使用未记录的功能,等等。仅支持六种按钮类型,这不是其中之一。

              【讨论】:

              • 按钮类型 101 似乎没有给我一个指向左的形状......只是一个矩形。
              • 不要这样做——您的应用将被拒绝。否决这个答案。
              • 我倾向于认为他不确定;他说“不要使用未记录的 API”,但没有说明他的应用程序被拒绝了。它不是一个未记录的 API——它是一个未记录的值。如果有人 拒绝了他们的应用,请发帖。我继续获得具有此值的应用程序批准。
              • @thefaj 我已经提交了一个包含此代码的应用程序,并且已获得批准。
              • 这是非常糟糕的编码风格。你很幸运,但你应该坚持只使用记录在案的 API(而不是魔法/未发布的数字)。
              【解决方案11】:

              我试图做同样的事情,但我希望后退按钮位于导航栏中。 (我实际上需要一个后退按钮,这不仅仅是返回,所以我不得不使用 leftBarButtonItem 属性)。我尝试了 AndrewS 的建议,但在导航栏中,它看起来不像它应该的样子,因为 UIButton 有点被强制转换为 UIBarButtonItem。

              但我找到了解决此问题的方法。我实际上只是在 UIButton 下放了一个 UIView,并为 UIBarButtonItem 设置了 customView。这是代码,如果有人需要的话:

              // initialize button and button view
              UIButton *backButton = [UIButton buttonWithType:101];
              UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backButton.frame.size.width, backButton.frame.size.height)];
              
              [backButton addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
              [backButton setTitle:@"Back" forState:UIControlStateNormal];
              [backButtonView addSubview:backButton];
              
              // set buttonview as custom view for bar button item
              UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
              self.navigationItem.leftBarButtonItem = backButtonItem;
              
              // push item to navigationbar items
              [self.navigationController.navigationBar setItems:[NSArray arrayWithObject:backButtonItem]];
              

              【讨论】:

                【解决方案12】:

                我发现使用以下简单的代码可以解决问题(需要捆绑包中的自定义图像):

                // Creates a back button instead of default behaviour (displaying title of previous screen)
                    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
                                                                                   style:UIBarButtonItemStyleBordered
                                                                                  target:self
                                                                                  action:@selector(backAction)];
                
                    tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
                    [backButton release];
                

                【讨论】:

                • 对于访问此页面的任何人,请将此答案与@PyjamaSam 的答案结合起来。
                • @PrairieHippo:现在已经完成了。可能应该首先被编辑。理想的 -1 表示一开始就不这样做,而将工作留给他人。
                【解决方案13】:
                    self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
                

                为我工作。当我有更多选项卡然后可以放在选项卡栏上时,我使用了这个,并且从“更多”推送的视图控制器覆盖了其 viewDidLoad 中的 leftBarButtonItem。

                【讨论】:

                  【解决方案14】:

                  这是我在搜索了所有这些解决方案和其他解决方案后最终做的事情。它使用从 UIKit 库存图像中提取的可拉伸 png。这样您就可以将文本设置为您喜欢的任何内容

                  // Generate the background images
                  UIImage *stretchableBackButton = [[UIImage imageNamed:@"UINavigationBarDefaultBack.png"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];
                  UIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@"UINavigationBarDefaultBackPressed.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
                  // Setup the UIButton
                  UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
                  [backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];
                  [backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];
                  NSString *buttonTitle = NSLocalizedString(@"Back", @"Back");
                  [backButton setTitle:buttonTitle forState:UIControlStateNormal];
                  [backButton setTitle:buttonTitle forState:UIControlStateSelected];
                  backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position
                  NSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);
                  [backButton setFrame:CGRectMake(0, 0, width, 29)];
                  backButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
                  [backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];
                  // Now add the button as a custom UIBarButtonItem
                  UIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
                  self.navigationItem.leftBarButtonItem = backButtonItem;
                  

                  【讨论】:

                  • 应该使用 UIControlStateHighlighted 而不是 UIControlStateSelected 否则当按钮被触摸时图像会交换。
                  【解决方案15】:

                  试试这个。我相信您不需要后退按钮图像来创建这样的图像。

                  UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                                 style:UIBarButtonItemStyleBordered
                                                                                target:self
                                                                                action:@selector(yourSelectorGoesHere:)];
                  self.navigationItem.backBarButtonItem = backButton;
                  

                  这就是你所要做的:)

                  【讨论】:

                    【解决方案16】:

                    我有一个类似的问题,出来一个图书馆PButton。示例是返回导航按钮,就像按钮一样,可以在任何地方使用,就像自定义按钮一样。

                    类似这样的:

                    【讨论】:

                      【解决方案17】:

                      首先,您必须找到返回按钮的图像。我使用了一个名为Extractor 的不错的应用程序,它可以从 iPhone 中提取所有图形。 在 iOS7 中,我设法检索到名为 UINavigationBarBackIndicatorDefault 的图像,它是黑色的,因为我需要一个红色调我使用 Gimp 将颜色更改为红色。

                      编辑:

                      正如btate 在他的评论中提到的,没有必要用图像编辑器改变颜色。以下代码应该可以解决问题:

                      imageView.tint = [UIColor redColor];
                      imageView.image = [[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                      

                      然后我创建了一个视图,其中包含一个带有该箭头的 imageView、一个带有自定义文本的标签,并且在视图顶部我有一个带有操作的按钮。然后我添加了一个简单的动画(淡入淡出和平移)。

                      以下代码模拟后退按钮的行为,包括动画。

                      -(void)viewWillAppear:(BOOL)animated{
                              UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"]];
                              [imageView setTintColor:[UIColor redColor]];
                              UILabel *label=[[UILabel alloc] init];
                              [label setTextColor:[UIColor redColor]];
                              [label setText:@"Blog"];
                              [label sizeToFit];
                      
                              int space=6;
                              label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
                              UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];
                      
                              view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);
                              [view addSubview:imageView];
                              [view addSubview:label];
                      
                              UIButton *button=[[UIButton alloc] initWithFrame:view.frame];
                              [button addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
                              [view addSubview:button];
                      
                              [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
                                  label.alpha = 0.0;
                                  CGRect orig=label.frame;
                                  label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
                                  label.alpha = 1.0;
                                  label.frame=orig;
                              } completion:nil];
                      
                              UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];
                      }
                      
                      - (void) handleBack:(id)sender{
                      }
                      

                      编辑:

                      我认为最好的方法是使用手势识别器,而不是添加按钮。

                      UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBack:)];
                      [view addGestureRecognizer:tap];
                      [view setUserInteractionEnabled:YES];
                      

                      【讨论】:

                      • 嗨,Alex,感谢您的解决方案。我在使用这个已实施的解决方案时面临的一个问题是:点击区域较少意味着当我点击箭头时,handleBack 不会被调用,但是当我点击文本时,handleBack 会被调用。请就此提出建议。谢谢
                      • 尝试使用 UITapGestureRecognizer 我编辑了问题
                      • 或许你也可以尝试增加视图的大小。
                      • 这个按钮上的黑色使它成为一个模板。你不需要使用 gimp 来改变它。只需在图像上使用 tint imageView.tint = [UIColor redColor] 和模板渲染模式。 imageView.image = [yourImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                      【解决方案18】:

                      使用 Xcode 5.x

                      中的 Interface Builder 很容易做到

                      • 使用 Object library

                        中的 ToolbarBar Button Item

                      • 在按钮的属性检查器编辑图像部分 你的返回按钮图片

                      完成!

                      【讨论】:

                        【解决方案19】:

                        使带有箭头的 UIButton 与 iOS 7 系统后退箭头非常接近(我不是设计师;):

                        标准:

                        Apple SD Gothic Neo

                        在 Xcode 中:

                        • 关注按钮的标题值字段(或任何其他带有文本内容的视图/控件)
                        • 打开编辑 -> 特殊字符
                        • 选择括号组并双击“
                        • 将字体更改为:Apple SD Gothic Neo,Regular,具有所需大小(例如 20)
                        • 随意改变颜色

                        在 iOS 7 上将 @staticVoidMan's answer 引用到类似返回的箭头

                        【讨论】:

                          【解决方案20】:

                          不使用 png 的解决方案。基于这个 SO 答案:Adding the little arrow to the right side of a cell in an iPhone TableView Cell

                          只是水平翻转 UITableViewCell!

                          UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 70, 20)];
                          
                          // Add the disclosure
                          CGRect frm;
                          UITableViewCell *disclosure = [[UITableViewCell alloc] init];
                          disclosure.transform = CGAffineTransformScale(CGAffineTransformIdentity, -1, 1);
                          frm = self.btnBack.bounds;
                          disclosure.frame = CGRectMake(frm.origin.x, frm.origin.y, frm.size.width-25, frm.size.height);
                          disclosure.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                          disclosure.userInteractionEnabled = NO;
                          [self.btnBack addSubview:disclosure];
                          
                          // Add the label
                          UILabel *lbl = [[UILabel alloc] init];
                          frm = CGRectOffset(self.btnBack.bounds, 15, 0);
                          lbl.frame = frm;
                          lbl.textAlignment = NSTextAlignmentCenter;
                          lbl.text = @"BACK";
                          [self addSubview:lbl];
                          

                          【讨论】:

                            【解决方案21】:

                            如果你不想打扰图像文件,可以使用以下代码在 UIView 子类中绘制箭头形状:

                            - (void)drawRect:(CGRect)rect {
                                float width = rect.size.width;
                                float height = rect.size.height;
                                CGContextRef context = UIGraphicsGetCurrentContext();
                            
                                CGContextBeginPath(context);
                                CGContextMoveToPoint(context, width * 5.0/6.0, height * 0.0/10.0);
                                CGContextAddLineToPoint(context, width * 0.0/6.0, height * 5.0/10.0);
                                CGContextAddLineToPoint(context, width * 5.0/6.0, height * 10.0/10.0);
                                CGContextAddLineToPoint(context, width * 6.0/6.0, height * 9.0/10.0);
                                CGContextAddLineToPoint(context, width * 2.0/6.0, height * 5.0/10.0);
                                CGContextAddLineToPoint(context, width * 6.0/6.0, height * 1.0/10.0);
                                CGContextClosePath(context);
                            
                                CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
                                CGContextFillPath(context);
                            }
                            

                            箭头视图与 6.0 的宽度和 10.0 的高度成正比

                            【讨论】:

                              【解决方案22】:

                              Swift 3 中的示例,右上角有一个上一个按钮和一个下一个按钮。

                              let prevButtonItem = UIBarButtonItem(title: "\u{25C0}", style: .plain, target: self, action: #selector(prevButtonTapped))
                              let nextButtonItem = UIBarButtonItem(title: "\u{25B6}", style: .plain, target: self, action: #selector(nextButtonTapped))
                              self.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]
                              

                              【讨论】:

                                【解决方案23】:

                                斯威夫特

                                // create button
                                    var backButton = UIButton(type: 101)
                                
                                    // left-pointing shape!
                                    backButton.addTarget(self, action: #selector(self.backAction), for: .touchUpInside)
                                    backButton.setTitle("Back", for: .normal)
                                
                                    // create button item -- possible because UIButton subclasses UIView!
                                    var backItem = UIBarButtonItem(customView: backButton)
                                
                                    // add to toolbar, or to a navbar (you should only have one of these!)
                                    toolbar.items = [backItem]
                                    navItem.leftBarButtonItem = backItem
                                

                                【讨论】:

                                  【解决方案24】:

                                  Swift 5.2 Xcode 11.4

                                  Apple 符号 chevron.left 现在允许更优雅的解决方案来制作自定义按钮。我已经尽可能地匹配了大小和间距。

                                  import UIKit
                                  
                                  class CustomBackButton: UIBarButtonItem {
                                  
                                      convenience init(target: Any, selector: Selector) {
                                  
                                          // Create UIButton
                                          let button = UIButton(frame: .zero)
                                  
                                          // Customise Title
                                          button.setTitle("Back", for: .normal)
                                          button.setTitleColor(.systemBlue, for: .normal)
                                          button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
                                  
                                          // Customise Image
                                          let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)
                                          let image = UIImage(systemName: "chevron.left", withConfiguration: config)
                                          button.setImage(image, for: .normal)
                                  
                                          // Add Target
                                          button.addTarget(target, action: selector, for: .touchUpInside)
                                  
                                          // Customise Spacing to match system Back button
                                          button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)
                                          button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)
                                  
                                          self.init(customView: button)
                                      }
                                  }
                                  

                                  这可以实现为UIToolbarItem,或UINavigationItem

                                  override func viewDidLoad() {
                                      super.viewDidLoad()
                                  
                                      // UIToolbar Item
                                      let barBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
                                      let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
                                      navigationController?.setToolbarHidden(false, animated: false)
                                      toolbarItems = [barBackButton, flexSpace]
                                  
                                      // Navigation Item
                                      let navBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
                                      navigationItem.leftBarButtonItem = navBackButton
                                  }
                                  
                                  @objc func backButtonTapped() {
                                      print("Back tapped")
                                  }
                                  

                                  如果你想翻转按钮并让箭头指向右边:

                                  使用名为 "chevron.right"

                                  的 Apple 符号

                                  将以下代码添加到CustomBackButton 类中:

                                      // Put the image of the right side of the button
                                      button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
                                      button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
                                      button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2012-05-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2023-04-01
                                    相关资源
                                    最近更新 更多