programing

iOS UIBarButtonItem의 제목 텍스트 제거

new-time 2020. 5. 9. 10:58
반응형

iOS UIBarButtonItem의 제목 텍스트 제거


내가하고 싶은

UIBarButtonItem

것은 탐색 표시 줄에 파란색 쉐브론 만 남기고 의 '뒤로'버튼에서 텍스트를 제거하는 것 입니다. iOS 7 용으로 개발 중임을 명심하십시오. 다음과 같은 여러 가지 방법을 시도했습니다.이것은 내가 좋아하지 않은 이미지 방법입니다 (이미지가 제대로 보이지 않았습니다).

UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iOS7BackButton"] style:UIBarButtonItemStylePlain target:self action:@selector(goToPrevious:)];
self.navigationItem.leftBarButtonItem = barBtnItem;

내가 시도한 또 다른 방법은 이것이 작동하지 않았습니다 (아무것도 표시되지 않음).

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc]init];
barBtn.title=@"";
self.navigationItem.leftBarButtonItem=barBtn;

내가 달성하고자하는 것은 단일 쉐브론 만 특징 인 iOS 7 Music 앱의 뒤로 버튼과 같은 것입니다. 감사.


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

그런 다음 뒤로 단추 항목 제목을 제거 할 수 있습니다. 스토리 보드를 사용하는 경우 탐색 속성 관리자 뒤로 버튼을 공백으로 설정할 수 있습니다.


제목을 변경하지 않고 뷰 컨트롤러의 뒤로 단추 제목을 설정하려면 다음을 사용하십시오.목표 -C :

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:self.navigationItem.backBarButtonItem.style target:nil action:nil];

빠른:

navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

분명히, 이것은 뒤로 버튼을 눌렀을 때 볼 수있는 뷰 컨트롤러에서 수행됩니다.

즉, '<Settings'를 보는 대신 '<'를보고 싶은 경우 SettingsViewController에서이를에 넣으십시오

init

. 그러면 뷰 컨트롤러 자체를 볼 때 제목에 표시되지 않는 문제가 발생하지 않습니다.


스토리 보드를 사용

Attributes Inspector

하는 경우 ViewController 로 이동하여

Navigation Item

(을 클릭

Navigation Bar

)

Back Button

속성을 ""(한 공백 문자)로 설정할 수 있습니다. 뒤로 단추 제목을 공백 문자 하나로 설정하여 갈매기 모양 표시를 유지합니다. 코드를 망칠 필요가 없습니다.

이미지 예

이렇게하면 이 Controller 내부에 표시 되는 것이 아니라 위에서 누른 View Controller에서이 View Controller에 표시되는 뒤로 단추의

Back Button

제목 이 설정 됩니다.

Back Button

 


이것은 텍스트없이 '뒤로'쉐브론을 표시하는 데 효과적입니다.

self.navigationController.navigationBar.topItem.title = @"";

 

viewDidLoad

탐색 막대를 표시하는 View Controller 에서이 속성을 설정 하면 트릭이 수행됩니다.참고 : iOS 7에서만 문제를 테스트했습니다.


버튼 제목을 설정할 때는 @ ""대신 @ ""를 사용하십시오.--편집하다--다른 줄을 시도 할 때 어떤 변화가 있습니까? 다음 코드를 성공적으로 사용하고 있습니다.

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:backString style:UIBarButtonItemStyleDone target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];

backString은 iOS 7 이하 버전인지에 따라 @ ""또는 @ "Back"으로 설정되는 변수입니다.한 가지 주목할 점은이 코드가 뒤로 버튼을 사용자 정의하려는 페이지의 컨트롤러에 없다는 것입니다. 실제로 네비게이션 스택에 컨트롤러 앞에 있습니다.


여기에 이미지 설명을 입력하십시오

때로는 상황에 맞는 것을 보는 것이 도움이됩니다. 다음은 "뒤로"텍스트를 숨기지 만 여전히 화살표를 표시하는 최소 프로젝트입니다.

스토리 보드

여기에 이미지 설명을 입력하십시오

"두 번째 뷰 컨트롤러 표시"버튼에서 두 번째 뷰 컨트롤러로 표시되는 쇼가 있습니다. 또한 제목을 갖도록 탐색 항목을 두 번째보기 컨트롤러에 추가했습니다. 이것은 선택 사항입니다. 뒤로 버튼에는 영향을 미치지 않습니다.

암호

FirstViewController.swift

import UIKit
class FirstViewController: UIViewController {

    @IBAction func showSecondViewControllerButtonTapped(sender: UIButton) {

        // hide the back button text
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}

SecondViewController.swift

import UIKit
class SecondViewController: UIViewController {
    // Nothing at all needed here
}

대체 방법 (IB 만, 코드 없음)

스토리 보드에서

첫 번째

보기 컨트롤러 (두 번째 아님) 의 탐색 항목을 선택하십시오 . 뒤로 버튼 텍스트를위한 공간을 입력하십시오.

여기에 이미지 설명을 입력하십시오


self.navigationController.navigationBar.topItem.title = @"";

iOS7에서 Apple은 UINavigationBar에 'backIndicatorTransitionMaskImage'와 'backIndicatorImage'라는 두 가지 새로운 속성을 도입했습니다.한 번만 호출하면

[[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"your_image"]];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"your_image_mask"]];

기본 쉐브론 글리프 대신 사용자 정의 이미지를 렌더링하여 keyWindow의 색조 색상을 상속합니다.제목을 제거하기 위해 Kamaros의 답변을 제안합니다. 새 뷰 컨트롤러를 푸시하는 뷰 컨트롤러에서이 코드를 호출해야합니다.

iOS UIBarButtonItem의 제목 텍스트 제거


제공된 답변으로 많은 성공을 거두지 못했지만 정말 간단한 해결책을 찾았습니다. 스토리 보드에서 UIViewController의 탐색 항목을 클릭하고 뒤로 버튼 텍스트를 설정할 수 있습니다. 나는 하나의 ''공간으로 설정하고 내가 찾던 행동을 주었다.

여기에 이미지 설명을 입력하십시오


이것은 iOS10에서 저에게 효과적이었습니다. 뷰 컨트롤러의 viewDidLoad에서 이것을 호출하십시오.

self.navigationController?.navigationBar.topItem?.title = ""

iOS7과 6에서 작동하는이 문제에 대한 간단한 해결책은 viewDidLoad에서 사용자 정의 제목보기를 설정하는 것입니다.

- (void)viewDidLoad {

    [super viewDidLoad];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.text = self.title;
    titleLabel.backgroundColor = [UIColor clearColor];

    [titleLabel sizeToFit];

    self.navigationItem.titleView = titleLabel;
}

그런 다음 viewWillAppear에서 안전하게 호출 할 수 있습니다.

self.navigationController.navigationBar.topItem.title = @" ";

제목보기는 사용자 정의보기이므로 탐색 스택에서 다시 이동할 때 제목보기를 덮어 쓰지 않습니다.


실제로 하나의 트릭 으로이 작업을 수행 할 수 있습니다.

UINavigationBar

클래스를 재정의 하고 다음 코드 줄을 추가하십시오.

- (void)layoutSubviews{
    self.backItem.title = @"";
    [super layoutSubviews];
}

그런 다음

UINavigationController

이 사용자 정의 UINavigationBar 클래스 등으로 초기화하십시오 .

UINavigationController * navController = [[UINavigationController alloc] initWithNavigationBarClass:[CBCNavigationBar class] toolbarClass:nil];

도움이 되었기를 바랍니다


나는 DonnaLea의 답변을 사용하여 무언가를 함께 모을 수있었습니다. 이것이 UIViewController 서브 클래스에 솔루션이 나타나는 방법입니다.

var backItemTitle:String?

override func viewDidLoad() {
    super.viewDidLoad()

    //store the original title
    backItemTitle = self.navigationController?.navigationBar.topItem?.title

    //remove the title for the back button
    navigationController?.navigationBar.topItem?.title = ""
}

override func willMoveToParentViewController(parent: UIViewController?) {
    super.willMoveToParentViewController(parent)
    if parent == nil {

        //restore the orignal title
        navigationController?.navigationBar.backItem?.title = backItemTitle
    }
}

원래 답변의 문제점은 다시 팝업하면 컨트롤러에서 제목을 제거한다는 것입니다. viewWillDisappear에서 제목을 재설정하려고하면 전환 프로세스에서 너무 늦습니다. 애니메이션 효과가 뛰어나지 않고 타이틀이 다시 스냅됩니다. 그러나 willMoveToParentViewController는 더 빨리 발생하고 올바른 동작을 허용합니다.주의 사항 : 나는 이것을 일반적인 UINavigationController 푸시 / 팝으로 만 테스트했습니다. 다른 상황에서는 예기치 않은 추가 동작이있을 수 있습니다.


첫 번째 ViewController의 PreparingForSegue : 메소드에서 뷰 제목을 @ ""로 설정하므로 다음 뷰를 누르면 이전 ViewController 제목 인 @ ""가 표시됩니다.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    self.navigationItem.title = @" ";
}

이것의 유일한 문제는 뒤로 버튼을 눌렀을 때 이전보기에 제목이 없으므로 viewWillAppear에 다시 추가 할 수 있다는 것입니다.

- (void)viewWillAppear:(BOOL)animated{
    self.navigationItem.title = @"First View Title";
}

나는이 솔루션을별로 좋아하지 않지만 작동하지만 다른 방법을 찾지 못했습니다.


스위프트 3

navigationController?.navigationBar.topItem?.title = ""

대답이 도움이되지 않았습니다. 그러나 속임수-방금 밀어보기 전에 뒤로 버튼이 밀린 뷰 컨트롤러의 제목을 지 웠습니다.따라서 이전보기에 제목이 없으면 iOS 7에서 뒤로 버튼에는 텍스트가없는 화살표 만 있습니다.

viewWillAppear

밀어보기, 나는 원래의 제목을 다시 배치.


    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor clearColor],UITextAttributeTextColor,
                                nil];

    [[UIBarButtonItem appearance] setTitleTextAttributes:attributes
                                                forState:UIControlStateNormal];

나는 같은 문제를 겪고 있었고 이렇게했다. --편집하다--이것은 모든 UIBarbuttonItem의 제목 텍스트를 정말로 제거하려는 경우의 해결책입니다. 뒤로 막대 단추 항목의 제목 만 제거하려는 경우 간단한 편리한 해결책이 없습니다. 필자의 경우 제목 텍스트를 표시 해야하는 UIBarButtonItems가 거의 없으므로 특정 버튼의 titleTextAttributes를 변경했습니다. 더 구체적으로하려면 아래 코드를 사용하십시오. 탐색 막대 버튼 만 변경됩니다.

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor clearColor],UITextAttributeTextColor,
                                nil];

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:attributes
                                                forState:UIControlStateNormal];

이것은 하위 클래스를 사용

navigationController

하여 "뒤로"를 제거합니다.앱을 통해 영구적으로 제거하는 데 사용하고 있습니다.

//.h
@interface OPCustomNavigationController : UINavigationController 

@end

//.m
@implementation OPCustomNavigationController

- (void)awakeFromNib
{
    [self backButtonUIOverride:YES];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [self backButtonUIOverride:NO];

    [super pushViewController:viewController animated:animated];
}

- (void)backButtonUIOverride:(BOOL)isRoot
{
    if (!self.viewControllers.count)
        return;

    UIViewController *viewController;

    if (isRoot)
    {
        viewController = self.viewControllers.firstObject;
    }
    else
    {
        int previousIndex = self.viewControllers.count - 1;

        viewController = [self.viewControllers objectAtIndex:previousIndex];
    }

    viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
                                                                                       style:UIBarButtonItemStylePlain
                                                                                      target:nil
                                                                                      action:nil];
}

@end

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefaultPrompt];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(10.0, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                               NSFontAttributeName:[UIFont systemFontOfSize:1]}
                                                    forState:UIControlStateNormal];

뒤로 단추 숨기기 탐색 표시 줄 제목

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @""; // blank or any other title
self.navigationController.navigationBar.topItem.backBarButtonItem = barButton;

여기 내가하고있는 일이 있는데, 뒤로 버튼의 제목을 제거하는 것이 더 간단합니다.

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.navigationBar?.backItem?.title = ""
}

Swift 3.1

UINavigationController의 delegate 메소드를 구현하여이를 수행 할 수 있습니다. 뒤로 버튼으로 제목 만 숨기고 뒤로 화살표 이미지와 기본 기능을 계속 사용할 수 있습니다.

func navigationController(_ navigationController: UINavigationController, 
  willShow viewController: UIViewController, animated: Bool) {
        let item = UIBarButtonItem(title: " ", style: .plain, target: nil, 
                    action: nil)
        viewController.navigationItem.backBarButtonItem = item
    }

이것을 사용할 수도 있습니다 :

UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
temporaryBarButtonItem.title = @"";
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;

[temporaryBarButtonItem release];

이것은 나를 위해 작동


case : <Back as <

override func viewWillAppear(animated: Bool) {
navigationController!.navigationBar.topItem!.title = ""
    }

전 세계적으로 완벽한 솔루션

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal)
    UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted)

    return true
}

나는 사용자 정의 클래스를 만들어

UINavigationController

내 앱의 모든 탐색 컨트롤러에 적용합니다. 이 사용자 정의

UINavigationController

클래스 내 에서 뷰가로드되면

UINavigationBar

델리게이트를 설정했습니다

self

.

- (void)viewDidLoad {
    self.navigationBar.delegate = self;
}

그런 다음 대리자 메서드를 구현합니다.

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item {

    // This will clear the title of the previous view controller
    // so the back button is always just a back chevron without a title
    if (self.viewControllers.count > 1) {
        UIViewController *previousViewController = [self.viewControllers objectAtIndex:(self.viewControllers.count - 2)];
        previousViewController.title = @"";
    }
    return YES;
}

This way I simply assign my custom class to all my navigations controllers and it clears the title from all the back buttons. And just for clarity, I always set the title for all my other view controllers inside viewWillAppear so that the title is always updated just before the view appears (in case it is removed by tricks like this).


Just entering a single space for the Back button navigation item works!!


If like me you're using a custom view instead of the UINavigationBar and you're stuck with the back button then you have to do a bit of work that feels a bit cludgey.

[self.navigationController.navigationBar setHidden:NO];
self.navigationController.navigationBar.topItem.title = @"";
[self.navigationController.navigationBar setHidden:YES];

It seems like if it doesn't get presented then no matter what it'll try show a title, this means it's shown then hidden before it's drawn and solves the problem.


extension UIViewController{
    func hideBackButton(){
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}

나는 모든 뒤로 버튼 제목을 숨기도록 매우 간단한 제로 구성 카테고리를 만들었습니다. 앱을 통해

여기에서

확인할 수 있습니다 . 이 질문은 이미 답변을 받았지만 다른 사람들에게는 도움이 될 수 있습니다.

편집하다:

.h 파일

#import <UIKit/UIKit.h>

@interface UINavigationController (HideBackTitle)
extern void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector);

@end

.m 파일

#import "UINavigationController+HideBackTitle.h"
#import <objc/runtime.h>


@implementation UINavigationController (HideBackTitle)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        PJSwizzleMethod([self class],
                    @selector(pushViewController:animated:),
                    @selector(pj_pushViewController:animated:));
    });
}

- (void)pj_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    UIViewController *disappearingViewController =  self.viewControllers.lastObject;
    if (disappearingViewController) {
        disappearingViewController.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    }
    if (!disappearingViewController) {
        return [self pj_pushViewController:viewController animated:animated];
    }
    return [self pj_pushViewController:viewController animated:animated];
}



@end

void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector)
{
    Method originalMethod = class_getInstanceMethod(cls, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);

    BOOL didAddMethod =
    class_addMethod(cls,
                originalSelector,
                method_getImplementation(swizzledMethod),
                method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {
        class_replaceMethod(cls,
                        swizzledSelector,
                        method_getImplementation(originalMethod),
                        method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

참고 URL :

https://stackoverflow.com/questions/19078995/removing-the-title-text-of-an-ios-uibarbuttonitem

반응형