사용자 정의 이미지가 있고 테두리가없는 UIBarButtonItem
사용자 지정 이미지로 UIBarButtonItem을 만들고 싶지만 내 이미지에 특수 테두리가 있기 때문에 iPhone이 추가하는 테두리를 원하지 않습니다.
뒤로 버튼과 동일하지만 앞으로 버튼입니다.
이 앱은 사내 프로젝트 용이므로 Apple이 거부하거나 승인하거나 좋아하든 상관 없습니다 :-)
UIBarButtonItem의 initWithCustomView : v 속성을 사용하면 다음과 같이 할 수 있습니다.
UIImage *image = [UIImage imageNamed:@"right.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
[button setBackgroundImage: [[UIImage imageNamed: @"right_clicked.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
[button addTarget:self action:@selector(AcceptData) forControlEvents:UIControlEventTouchUpInside];
UIView *v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
[v addSubview:button];
UIBarButtonItem *forward = [[UIBarButtonItem alloc] initWithCustomView:v];
self.navigationItem.rightBarButtonItem= forward;
[v release];
[image release];
작동하지만 10 개의 뷰에서이 과정을 반복해야한다면 DRY가 아닙니다.
나는 하위 클래스를해야한다고 생각하지만 무엇?
- NSView?
- UIBarButtonItem?
감사,
문안 인사,
사용자 정의 범주를 사용하여 하위 클래스 화하지 않고 UIBarButtonItem에 메서드를 추가 할 수 있습니다.
@interface UIBarButtonItem(MyCategory)
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action;
@end
@implementation UIBarButtonItem(MyCategory)
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action{
// Move your item creation code here
}
@end
따라서 코드의 모든 위치에서이 메서드를 호출하는 막대 항목을 만들 수 있습니다 (선언에 헤더를 포함하는 경우).
추신 : 'v'UIView를 사용할 필요는 없습니다 UIBarButtonItem
. 버튼으로 직접 커스텀 뷰로 만들 수 있습니다.
PPS 코드에 [forward release]도 필요합니다.
또 다른 간단한 해결책은
- 표준 UIButton 드래그
- 버튼의 스타일을 사용자 지정으로 설정하고 해당 버튼의 이미지를 설정합니다.
- UINavigationBar로 드래그하세요.
- 선택기 설정
나는이 방법이 쉽다는 것을 알았다. 그것은 상단에 포획됩니다. "random.png"는 프로젝트에 있어야합니다. 이미지를 끌어서 놓기 만하면됩니다.
UIButton *a1 = [UIButton buttonWithType:UIButtonTypeCustom];
[a1 setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];
[a1 addTarget:self action:@selector(randomMsg) forControlEvents:UIControlEventTouchUpInside];
[a1 setImage:[UIImage imageNamed:@"config.png"] forState:UIControlStateNormal];
UIBarButtonItem *random = [[UIBarButtonItem alloc] initWithCustomView:a1];
//? line incomplete ?// imageNamed:@"random.png"] style:UIBarButtonItemStylePlain target:self action:@selector(randomMsg)];
self.navigationItem.rightBarButtonItem = random;
An alternative is to subclass UIBarButtonItem. Why? So that the action is invoked on the target with the correct sender. In the code above, the sender argument in the action message is the UIButton instance, not the UIBarButtonItem instance. This would be important, for example, if you wish to present a UIPopoverController from the bar button item. By subclassing UIBarButtonItem, you can add an ivar that retains the original target, allowing our subclass instances to intercept, modify, and forward the action message with the proper sender.
So, CCFBarButtonItem.h:
#import <uIKit/UIBarButtonItem.h>
@interface CCFBarButtonItem : UIBarButtonItem
{
@protected
id _originalTarget;
}
- (id)initWithImage:(UIImage *)image target:(id)target action:(SEL)action;
@end
and CCFBarButtonItem.m
#import "CCFBarButtonItem.h"
#import <UIKit/UIButton.h>
#import <UIKit/UIView.h>
#import <UIKit/UIImage.h>
@implementation CCFBarButtonItem
#pragma mark - Object life cycle
- (id)initWithImage:(UIImage *)image target:(id)target action:(SEL)action;
{
_ASSIGN( _originalTarget, target );
UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imgButton setImage:image forState:UIControlStateNormal];
imgButton.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
[imgButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
self = [super initWithCustomView:imgButton];
return self;
}
- (void)dealloc;
{
MCRelease(_originalTarget);
[super dealloc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
{
if( [_originalTarget respondsToSelector:aSelector] )
{
return [_originalTarget methodSignatureForSelector:aSelector];
}
else
{
return [super methodSignatureForSelector:aSelector];
}
}
- (void)forwardInvocation:(NSInvocation *)anInvocation;
{
SEL aSelector = [anInvocation selector];
if( [_originalTarget respondsToSelector:aSelector] )
{
// modify the 'sender' argument so that it points to self
[anInvocation setArgument:&self atIndex:2];
[anInvocation invokeWithTarget:_originalTarget];
}
else
{
[self doesNotRecognizeSelector:aSelector];
}
}
@end
UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:@"icon-menu.png"]
style:UIBarButtonItemStylePlain
target:self
action:@selector(showMenu)];
This can also be done programmatically as well (of-course):
First, create a custom view. This custom view can contain an image, button or whatever else you would like. The custom view can be made programmatically or in IB:
UIImage *customImage = [UIImage imageNamed:@"imageName"];
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, customImage.size.width, customImage.size.height)];
customView.backgroundColor = [UIColor colorWithPatternImage:customImage];
Next, create a UIBarButtonItem and initialize it with the custom view.
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
Now, just add the custom UIBarButton to the leftBarButtonItem:
self.navigationItem.leftBarButtonItem = customBarButtonItem;
Ok that category works very good because there are no problems with Popovercontroller :-)
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (BarButtonItemExtended)
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action;
-(void)performBarButtonAction:(id)sender;
@end
#import "UIBarButtonItem+BarButtonItemExtended.h"
@implementation UIBarButtonItem (BarButtonItemExtended)
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action
{
UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imgButton setImage:image forState:UIControlStateNormal];
imgButton.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIBarButtonItem *b = [[UIBarButtonItem alloc]initWithCustomView:imgButton];
[imgButton addTarget:b action:@selector(performBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[b setAction:action];
[b setTarget:target];
return b;
}
-(void)performBarButtonAction:(UIButton*)sender
{
[[self target] performSelector:self.action withObject:self];
}
@end
Check this out simple solution.
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
barButtonItem.image = [UIImage imageNamed:@"navButton.png"];
barButtonItem.style = UIBarButtonItemStylePlain;
[barButtonItem setBackgroundImage:[UIImage imageNamed:@"1x1.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}
Here 1x1.png is a 1 pixel transparent png image which you can download from the link below
http://commons.wikimedia.org/wiki/File:1x1.png
One another solution, think it's simpler in case when creating button programatically:
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:defaultImage
landscapeImagePhone:landscapeImage
style:UIBarButtonItemStylePlain
target:self
action:@selector(someSelector)];
[button setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[button setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
참고URL : https://stackoverflow.com/questions/2681321/uibarbuttonitem-with-custom-image-and-no-border
'Programing' 카테고리의 다른 글
ImmutableMap 또는 Map을 반환하는 것이 더 낫습니까? (0) | 2020.09.10 |
---|---|
jquery를 사용하여 iframe의 콘텐츠를 동적으로 변경하려면 어떻게해야합니까? (0) | 2020.09.10 |
게터, 세터 및 속성 모범 사례. (0) | 2020.09.10 |
C ++에서 구조체를 비교하는 동안 == 연산자가 없습니다. (0) | 2020.09.09 |
CSS로 비스듬히 치는 방법 (0) | 2020.09.09 |