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

UIBarButtonItem: Как я могу найти его фрейм?

У меня есть кнопка на панели инструментов. Как я могу захватить его рамку? У UIBarButtonItem нет свойства frame?

4b9b3361

Ответ 1

Попробуйте это:

UIBarButtonItem *item = ... ;
UIView *view = [item valueForKey:@"view"];
CGFloat width;
if(view){
    width=[view frame].size.width;
}
else{
    width=(CGFloat)0.0 ;
}

Ответ 2

Этот способ работает лучше всего для меня:

UIView *targetView = (UIView *)[yourBarButton performSelector:@selector(view)];
CGRect rect = targetView.frame;

Ответ 3

Спасибо Аноопу Вайдя за предложенный ответ. Альтернативой может быть (если вы знаете положение кнопки на панели инструментов)

UIView *view= (UIView *)[self.toolbar.subviews objectAtIndex:0]; // 0 for the first item


CGRect viewframe = view.frame;

Ответ 4

С Swift, если вам нужно часто работать с элементами кнопки, вам следует реализовать расширение следующим образом:

extension UIBarButtonItem {

    var frame: CGRect? {
        guard let view = self.value(forKey: "view") as? UIView else {
            return nil
        }
        return view.frame
    }

}

Тогда в вашем коде вы можете легко получить доступ:

if let frame = self.navigationItem.rightBarButtonItems?.first?.frame {
    // do whatever with frame            
}

Ответ 5

-(CGRect) getBarItemRc :(UIBarButtonItem *)item{
    UIView *view = [item valueForKey:@"view"];
    return [view frame];
}

Ответ 6

Попробуйте выполнить эту реализацию:

@implementation UIBarButtonItem(Extras)

- (CGRect)frameInView:(UIView *)v {

    UIView *theView = self.customView;
    if (!theView.superview && [self respondsToSelector:@selector(view)]) {
        theView = [self performSelector:@selector(view)];
    }

    UIView *parentView = theView.superview;
    NSArray *subviews = parentView.subviews;

    NSUInteger indexOfView = [subviews indexOfObject:theView];
    NSUInteger subviewCount = subviews.count;

    if (subviewCount > 0 && indexOfView != NSNotFound) {
        UIView *button = [parentView.subviews objectAtIndex:indexOfView];
        return [button convertRect:button.bounds toView:v];
    } else {
        return CGRectZero;
    }
}

@end

Ответ 7

Вы должны сделать цикл над subviews и проверить их тип или их содержимое для идентификации. Невозможно получить доступ к представлению kvo, и вы не можете быть уверены в индексе.

Ответ 9

Вы можете создать UIBarButtonItem с настраиваемым представлением, которое является UIButton, тогда вы можете делать все, что хотите.:]

Ответ 10

Oof, много грубых ответов в этой теме. Вот правильный способ сделать это:

import UIKit

class ViewController: UIViewController {

    let customButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()

        customButton.setImage(UIImage(named: "myImage"), for: .normal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: customButton)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print(self.customButton.convert(self.customButton.frame, to: nil))
    }
}