Programing

UIBarButtonItem : 대상 작업이 작동하지 않습니까?

lottogame 2020. 10. 16. 07:03
반응형

UIBarButtonItem : 대상 작업이 작동하지 않습니까?


UIBarButtonItem을 호출 하여 설정 한 내부에 사용자 정의보기가 있습니다 -initWithCustomView. 내 바 버튼 항목은 잘 렌더링되지만 탭하면 대상 개체에 대한 작업이 호출되지 않습니다.

내 코드는 다음과 같습니다.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someImage.png"]];
UIBarButtonItem *bbItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
self.navigationItem.leftBarButtonItem = bbItem;
[imageView release];
[bbItem setTarget:self];
[bbItem setAction:@selector(deselectAll)];

UIBarButtonItem의 대상과 동작이 사용자 지정보기에 적용되지 않는다고 생각합니다. UIImageView 대신 UIButton을 사용하고 버튼에 대상과 작업을 적용 해보십시오.

Swift의 샘플 코드 :

let button  = UIButton(type: .Custom)
if let image = UIImage(named:"icon-menu.png") {
    button.setImage(image, forState: .Normal)
}
button.frame = CGRectMake(0.0, 0.0, 30.0, 30.0)
button.addTarget(self, action: #selector(MyClass.myMethod), forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem(customView: button)
navigationItem.leftBarButtonItem = barButton

나는 같은 문제가 있었지만 UIButtonUIBarButtonItem(drawonward의 응답에 따라) 사용자 정의보기 대신 사용하는 것을 싫어했습니다 .

또는 UIGestureRecognizer초기화에 사용하기 전에 사용자 정의보기에를 추가 할 수 있습니다 UIBarButtonItem. 이것은 내 프로젝트에서 작동하는 것 같습니다.

이것은 원래 코드를 수정하는 방법입니다.

UIImageView *SOCImageView = [[UIImageView alloc] initWithImage:
                             [UIImage imageNamed:@"cancel_wide.png"]];

UITapGestureRecognizer *tapGesture = 
       [[UITapGestureRecognizer alloc] initWithTarget:self 
                                               action:@selector(deselectAll:)];
[SOCImageView addGestureRecognizer:tapGesture];

SOItem.leftBarButtonItem = 
       [[[UIBarButtonItem alloc] initWithCustomView:SOCImageView] autorelease];
[tapGesture release];
[SOCImageView release];

작동 방식은 다음과 같습니다.

UIButton* infoButton = [UIButton buttonWithType: UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(displayAboutUs) forControlEvents:UIControlEventTouchDown];

UIBarButtonItem* itemAboutUs =[[UIBarButtonItem alloc]initWithCustomView:infoButton];

다음은 UIBarButtonItem 내부에 UIButton을 구현 한 방법입니다.

UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoButton setImage: [UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
logoButton.frame = CGRectMake(0, 0, 30, 30);
[logoButton addTarget:self action:@selector(showAbout:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
self.navigationItem.rightBarButtonItem = barItem;
[barItem release];

비슷한 문제가있었습니다. 그리고 처음에는 @drawnonward가 제안한 경로를 따랐지만 iPad에 팝 오버 컨트롤러를 표시하려고 할 때 문제가 발생했습니다. 내장 된 UIButton을 사용자 정의보기로 사용하면 UIButton이 이벤트의 발신자임을 의미합니다. 팝 오버 컨트롤러의 presentPopoverFromBarButtonItem : 메서드는 실제 UIBarButtonItems에만 적합한 메시지를 보내려고 할 때 충돌합니다.

결국 내가 찾은 해결책은 일회용 UIButton에서 사용하려는 이미지 ( "정보"아이콘)를 훔치고 다음과 같이 내 UIBarButtonItem을 구성하는 것입니다.

// Make the info button use the standard icon and hook it up to work
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
UIBarButtonItem *barButton = [[[UIBarButtonItem alloc]        
      initWithImage:infoButton.currentImage
              style:UIBarButtonItemStyleBordered
             target:self
             action:@selector(showInfo:)] autorelease];

이 이니셜 라이저를 사용하면 타겟과 선택기가 실제로 작동하는 바 버튼이 생성됩니다. 사용자 정의보기에서 이미지를 래핑하는 것보다 더 쉽지만 그것은 단지 장식 일뿐입니다.


Jacob, everything looks good, however you may not have provided the correct selector.

Can you verify that your action is actually declared

- (void) deselectAll;

and not

- (void) deselectAll:(id)sender;

If it's the latter, you will need to set the action to @selector(deselectAll:). (note the semi-colon to match the method declaration)

Also, void might be IBAction, but that's not relevant to this problem you're having.


Swift 3. I had a similar issue where I had a custom view inside of the bar button item. In order to get the tap to work I assigned a gesture to the view and set the action. The view needed to be an outlet to assign to it. Doing this it worked with the custom view.

Setting the gesture as class variable

@IBOutlet weak var incidentView: UIView!
let incidentTap = UITapGestureRecognizer()

In viewDidLoad

incidentTap.addTarget(self, action: #selector(self.changeIncidentBarItem))
incidentView.addGestureRecognizer(incidentTap)

If you do not want to settle with an UIImage and have a custom view in your barbuttonitem, set a tap gesture recognizer to your barbuttonitem's customview property

let tap = UITapGestureRecognizer(target: self, action: #selector(goProButtonPressed)) deviceStatusBarButtonItem.customView?.addGestureRecognizer(tap)


Swift 3 : Below is my full implementation for button customization and event handling.

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton.init(type: .custom)
    button.setTitle("Tester", for: .normal)
    button.setTitleColor(.darkGray, for: .normal)
    button.layer.borderWidth = 1
    button.layer.cornerRadius = 5
    button.layer.borderColor = UIColor.darkGray.cgColor
    button.addTarget(self, action: #selector(self.handleButton), for: .touchUpInside)

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let button = self.navigationItem.rightBarButtonItem?.customView {
        button.frame = CGRect(x:0, y:0, width:80, height:34)
    }
}

func handleButton( sender : UIButton ) {
    // It would be nice is isEnabled worked...
    sender.alpha = sender.alpha == 1.0 ? 0.5 : 1.0
}

Hope this helps


Is your custom view eating touch events or passing them on to parent view?


To make this easy to work with, I created a category on UIBarButtonItem which looks like this:

@implementation UIBarButtonItem (CustomButtonView)

- (void)setButtonImage:(UIImage *)image
{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button sizeToFit];
    [button addTarget:self.target action:self.action forControlEvents:UIControlEventTouchUpInside];
    self.customView = button;
}

- (UIImage *)buttonImage
{
    return [(UIButton *)self.customView imageForState:UIControlStateNormal];
}

@end

In your client code, simply use:

myBarButtonItem.buttonImage = [UIImage imagedNamed:@"image_name"];

Done this way you can still hook up your targets and actions in IB (pushing as much UI config into IB as you can is a Good Thing).

참고URL : https://stackoverflow.com/questions/2796438/uibarbuttonitem-target-action-not-working

반응형