ProgramingTip

UIBarButton

bestdevel 2020. 12. 3. 08:18
반응형

UIBarButton


버튼이 있습니다. 프레임을 어떻게 잡을 수 있습니까? 음주 UIBarButtonItem하지 s의 frame속성을?


이걸로 해봐;

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

이 방법이 가장 적합합니다.

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

제안 된 답변에 대해 Anoop Vaidya에게 감사드립니다. 대안은 다음과 가능합니다 (도구 모음에서 버튼의 위치를 ​​알고있는 경우).

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


CGRect viewframe = view.frame;

이 경우 많은 사람들이 있습니다. 올바른 방법은 다음과 가능합니다.

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))
    }
}

함께 스위프트 자주 바 버튼 항목으로 할 필요가있는 경우 작업은 같은 확장을 구현해야합니다.

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            
}

다음은 iOS 11 및 Swift 4에서 사용하는 것입니다. 선택 사항 없이는 조금 더 깔끔하게 할 수 있도록 준비하고 있습니다.

extension UIBarButtonItem {
    var view: UIView? {
        return perform(#selector(getter: UIViewController.view)).takeRetainedValue() as? UIView
    }
}

그리고 사용법 :

if let barButtonFrame = myBarButtonItem.view?.frame {
    // etc...
}

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

이 구현을 시도하십시오.

@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

하위보기에 대해 루프를 수행하고 식별을 위해 해당 유형 또는 내용을 확인해야합니다. kvo로보기에 액세스하는 것은 안전하지 않으며 색인에 대해 확신 할 수 없습니다.


이 답변을 확인하십시오 : UIBarButtonItem에 테두리와 모서리 반경을 적용하는 방법? 버튼의 프레임을 찾기 위해 하위보기를 반복하는 방법을 설명합니다.


UIButton 인 사용자 지정보기를 사용하여 UIBarButtonItem을 만든 다음 원하는 모든 작업을 수행 할 수 있습니다. :]


Swift 4.2에서 luca에서 영감을 받았습니다

extension UIBarButtonItem {

    var frame:CGRect?{
        return (value(forKey: "view") as? UIView)?.frame
    }

}


guard let frame = self.navigationItem.rightBarButtonItems?.first?.frame else{ return }

Human Interface Guidelines의 아이콘 크기 가이드와 결합 된 navigationBar layoutMargins같은 속성을 사용하여 대략적 으로 계산하고 현재 장치 방향을 계산할 수 있습니다.frame

- (CGRect)rightBarButtonFrame {
    CGFloat imageWidth = 28.0;
    CGFloat imageHeight = UIDevice.currentDevice.orientation == UIDeviceOrientationLandscapeLeft || UIDevice.currentDevice.orientation == UIDeviceOrientationLandscapeRight ? 18.0 : 28.0;
    UIEdgeInsets navigationBarLayoutMargins = self.navigationController.navigationBar.layoutMargins;
    CGRect navigationBarFrame = self.navigationController.navigationBar.frame;
    return CGRectMake(navigationBarFrame.size.width-(navigationBarLayoutMargins.right + imageWidth), navigationBarFrame.origin.y + navigationBarLayoutMargins.top, imageWidth, imageHeight);
}

방법은 다음과 같습니다.

-(CGRect)findFrameOfBarButtonItem{
    for (UIView *view in self.navigationController.navigationBar.subviews)
    {
       if ([view isKindOfClass:NSClassFromString(@"_UINavigationBarContentView")])
       {
         UIView * barView = [self.navigationItem.rightBarButtonItem valueForKey:@"view"];
         CGRect barFrame = barView.frame;
         CGRect viewFrame = [barView convertRect:barFrame toView:view];
         return viewFrame;
       }
    }

    return CGRectZero;
}

참고 URL : https://stackoverflow.com/questions/14318368/uibarbuttonitem-how-can-i-find-its-frame

반응형