Подтвердить что ты не робот

Добавление UILabel в UIToolbar

Я пытаюсь добавить ярлык на свою панель инструментов. Кнопка работает отлично, однако, когда я добавляю объект метки, он падает. Любые идеи?

UIBarButtonItem *setDateRangeButton = [[UIBarButtonItem alloc] initWithTitle:@"Set date range"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(setDateRangeClicked:)];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
label.text = @"test";

[toolbar setItems:[NSArray arrayWithObjects:setDateRangeButton,label, nil]];

// Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];

// Reload the table view
[self.tableView reloadData];
4b9b3361

Ответ 1

Взгляните на это

[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];

По сути, каждый элемент должен быть "button", но они могут быть созданы с любым видом, который вам нужен. Вот пример кода. Обратите внимание, так как другие кнопки обычно находятся на панели инструментов, распорки располагаются с каждой стороны кнопки заголовка, поэтому они остаются центрированными.

NSMutableArray *items = [[self.toolbar items] mutableCopy];

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer];
[spacer release];

self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)];
[self.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
[self.titleLabel setBackgroundColor:[UIColor clearColor]];
[self.titleLabel setTextColor:[UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]];
[self.titleLabel setText:@"Title"];
[self.titleLabel setTextAlignment:NSTextAlignmentCenter];

UIBarButtonItem *spacer2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer2];
[spacer2 release];

UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:self.titleLabel];
[items addObject:title];
[title release];

[self.toolbar setItems:items animated:YES];
[items release];

Ответ 2

Для тех, кто использует Interface Builder для компоновки вашего UIToolBar, это также можно сделать с помощью Interface Builder.

Чтобы добавить UILabel в UIToolBar, вам нужно добавить общий UIView объект к вашему UIToolBar в IB, перетащив новый объект UIView поверх вашего UIToolBar. IB автоматически создаст UIBarButtonItem, который будет инициализирован вашим пользовательским UIView. Затем добавьте UILabel в UIView и отредактируйте UILabel графически в соответствии с вашим предпочтительным стилем. Затем вы можете визуально настроить свои фиксированные и/или переменные разделители по желанию, чтобы правильно разместить ваш UILabel.

Вы также должны установить фон как UILabel, так и UIView на clearColor, чтобы получить UIToolBar для корректного отображения в UILabel.

Ответ 3

Я нашел answerBot ответ очень полезным, но я думаю, что нашел еще более простой способ в Interface Builder:

  • создать UIBarButtonItem и добавить его на панель инструментов в интерфейсе Builder

enter image description here

  • Снимите флажок "enabled" для этого BarButtonItem

enter image description here

  • подключите этот BarButtonItem к свойству в вашем классе (это находится в Swift, но будет очень похож на Obj-C):

    @IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel
    
  • добавить другое свойство для самой метки:

    private var lastUpdateLabel = UILabel(frame: CGRectZero)
    
  • в viewDidLoad, добавьте следующий код, чтобы установить свойства вашего label и добавьте его как customView вашего BarButtonItem

    // Dummy button containing the date of last update
    lastUpdateLabel.sizeToFit()
    lastUpdateLabel.backgroundColor = UIColor.clearColor()
    lastUpdateLabel.textAlignment = .Center
    lastUpdateButton.customView = lastUpdateLabel
    
  • Чтобы обновить текст UILabel:

    lastUpdateLabel.text = "Updated: 9/12/14, 2:53"
    lastUpdateLabel.sizeToFit() 
    

Результат:

enter image description here

Вы должны называть lastUpdateLabel.sizetoFit() каждый раз, когда вы обновляете текст метки

Ответ 4

Одна из вещей, которыми я использую этот трюк, - это создать экземпляр UIActivityIndicatorView поверх UIToolBar, что в противном случае было бы невозможно. Например, здесь у меня есть UIToolBar с 2 UIBarButtonItem, a FlexibleSpaceBarButtonItem, а затем еще один UIBarButtonItem. Я хочу вставить UIActivityIndicatorView в UIToolBar между гибким пространством и конечной (правой кнопкой). Поэтому в моем RootViewController я делаю следующее,

- (void)viewDidLoad {
[super viewDidLoad];// Add an invisible UIActivityViewIndicator to the toolbar
UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:767];
NSArray *items = [toolbar items];

activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];    

NSArray *newItems = [NSArray arrayWithObjects:[items objectAtIndex:0],[items objectAtIndex:1],[items objectAtIndex:2],
                     [[UIBarButtonItem alloc] initWithCustomView:activityIndicator], [items objectAtIndex:3],nil];
[toolbar setItems:newItems];}

Ответ 5

По аналогии с Matt RI используется конструктор интерфейсов. Но вместо этого я хотел, чтобы внутри был 1 UIWebView чтобы текст можно было выделить жирным шрифтом, а другой - нет (например, почтовое приложение). Так

  1. Вместо этого добавьте веб-просмотр.
  2. Снимите флажок непрозрачный
  3. Убедитесь, что фон имеет чистый цвет
  4. Подключите все с IBOutlet
  5. Используйте html ниже, чтобы иметь прозрачный фон, чтобы панель инструментов просвечивала

Код:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *html = [NSString stringWithFormat:@"<html><head><style>body{font-size:11px;text-align:center;background-color:transparent;color:#fff;font-family:helvetica;vertical-align:middle;</style> </head><body><b>Updated</b> 10/11/12 <b>11:09</b> AM</body></html>"];
[myWebView loadHTMLString:html baseURL:baseURL];

Ответ 6

Добавьте UILabel к UIToolbar программно, используя swift 3

Полный пример

import UIKit

class ViewController: UIViewController {

    var toolBar: ToolBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        toolBar = ToolBar(bottomBarWithHeight: 44, target: self)
        view.addSubview(toolBar!)

        toolBar.appendButton(buttonItem: toolBar.buttonItem(systemItem: .add, selector: #selector(ViewController.action)))
        toolBar.appendButton(buttonItem: toolBar.buttonItem(systemItem: .camera, selector: #selector(ViewController.action)))
        toolBar.appendButton(buttonItem: toolBar.flexibleSpace)
        toolBar.appendButton(buttonItem: toolBar.titleItem(text: "\(NSDate())", font: UIFont.systemFont(ofSize: 12), color: UIColor.lightGray))
        toolBar.appendButton(buttonItem: toolBar.flexibleSpace)
        toolBar.appendButton(buttonItem: toolBar.buttonItem(systemItem: .cancel, selector: #selector(ViewController.action)))
    }

    func action() {
        print("action")
    }

}

class ToolBarTitleItem: UIBarButtonItem {

    var label: UILabel

    init(text: String, font: UIFont, color: UIColor) {

        label =  UILabel(frame: UIScreen.main.bounds)
        label.text = text
        label.sizeToFit()
        label.font = font
        label.textColor = color
        label.textAlignment = .center

        super.init()

        customView = label
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ToolBar: UIToolbar {

    let target: Any?

    init(bottomBarWithHeight: CGFloat, target: Any?) {
        self.target = target

        var bounds =  UIScreen.main.bounds
        bounds.origin.y = bounds.height - bottomBarWithHeight
        bounds.size.height = bottomBarWithHeight

        super.init(frame: bounds)
    }

    init(frame: CGRect, target: Any?) {
        self.target = target
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func buttonItem(systemItem: UIBarButtonSystemItem, selector: Selector?) -> UIBarButtonItem {
        return UIBarButtonItem(barButtonSystemItem: systemItem, target: target, action: selector)
    }

    var flexibleSpace: UIBarButtonItem {
        return buttonItem(systemItem: UIBarButtonSystemItem.flexibleSpace, selector:nil)
    }

    func titleItem (text: String, font: UIFont, color: UIColor) -> UIBarButtonItem {
        return ToolBarTitleItem(text: text, font: font, color: color)
    }

    func appendButton(buttonItem: UIBarButtonItem) {
        if items == nil {
            items = [UIBarButtonItem]()
        }

        items!.append(buttonItem)
    }
}

Результат

enter image description here

Ответ 7

Попробуйте следующее:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140 , 0, 50, 250)];
[label setBackgroundColor:[UIColor clearColor]];
label.text = @"TEXT";
UIView *view = (UIView *) label;
[self.barItem setCustomView:view];

Примечание: self.barItem - это UIBarButtonItem, добавленный из библиотеки объектов и помещенный между двумя гибкими пространствами.

Другой способ - удалить строку [self.barItem setCustom:view] и изменить параметры label (width), чтобы заполнить всю панель инструментов и установить выравнивание по середине и шрифту самостоятельно в коде,

Ответ 8

Если вы хотите добавить представление в панель инструментов, вы можете попробовать следующее:

[self.navigationController.tabBarController.view addSubview:yourView];