Programing

이미지와 레이블로 사용자 정의 UIBarButtonItem을 만드는 방법은 무엇입니까?

lottogame 2020. 11. 23. 07:35
반응형

이미지와 레이블로 사용자 정의 UIBarButtonItem을 만드는 방법은 무엇입니까?


다음과 같이 이미지와 텍스트를 모두 포함하는 사용자 지정 UIBarButtonItem을 만들고 싶습니다.

여기에 이미지 설명 입력

UIBarButtonItem을 서브 클래 싱하고이 메서드를 재정의하려고했습니다.

- (UIView *)customView
{
    if (!self.storedView) {

        UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
        UIImageView *tempImageView = [[UIImageView alloc] initWithImage:self.image];
        tempImageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
        tempLabel.text = @"text";
        [temp addSubview:tempImageView];
        [temp addSubview:tempLabel];
        self.storedView = temp;
    }
    return self.storedView;
}

그리고 나는 이것을 다음과 같이 사용합니다.

UIBarButtonItem *left = [[LeftItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsPressed)];
left.title = @"Settings";
left.image = [UIImage imageNamed:@"settings.png"];
self.navigationItem.leftBarButtonItem = left;

그러나 이것을 사용하면 이미지 만 얻지 만 레이블은 얻지 못합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?


UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;

에 사용자 정의보기를 추가 할 수 있습니다 UIBarButtonItem.

iOS 7에는 목적에 맞는 새로운 buttonType이 호출 UIButtonTypeSystem됩니다 UIButton. 이 시도,

UIView* leftButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];

UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
leftButton.backgroundColor = [UIColor clearColor];
leftButton.frame = leftButtonView.frame;
[leftButton setImage:[UIImage imageNamed:<YourImageName>] forState:UIControlStateNormal];
[leftButton setTitle:@"YourTitle" forState:UIControlStateNormal];
leftButton.tintColor = [UIColor redColor]; //Your desired color.
leftButton.autoresizesSubviews = YES;
leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
[leftButton addTarget:self action:@selector(<YourTargetMethod>) forControlEvents:UIControlEventTouchUpInside];
[leftButtonView addSubview:leftButton];

UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftButtonView];
self.navigationItem.leftBarButtonItem = leftBarButton;

업데이트 된 Swift 코드,

let leftButtonView = UIView.init(frame: CGRect(x: 0, y: 0, width: 110, height: 50))

let leftButton = UIButton.init(type: .system)
leftButton.backgroundColor = .clear
leftButton.frame = leftButtonView.frame
leftButton.setImage(UIImage.init(imageLiteralResourceName: <YourImageName>), for: .normal)
leftButton.setTitle("YourTitle", for: .normal)
leftButton.tintColor = .red //Your desired color.
leftButton.autoresizesSubviews = true
leftButton.autoresizingMask = [.flexibleWidth , .flexibleHeight]
leftButton.addTarget(self, action: #selector(<YourTargetMethod>), for: .touchUpInside)
leftButtonView.addSubview(leftButton)

let leftBarButton = UIBarButtonItem.init(customView: leftButtonView)
navigationItem.leftBarButtonItem = leftBarButton

BarButtonItem이 Storyboard에있는 경우 다른 Button을 BarButtonItem으로 끌어 올 수 있으므로 BarButtonItem 내에 Button이 있으므로 이미지와 레이블을 모두 단추에 추가 할 수 있습니다.


SWIFT 버전

    let button =  UIButton(type: .Custom)
    button.setImage(UIImage(named: "icon_right"), forState: .Normal)
        button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(0, 0, 53, 31)
    button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
    let label = UILabel(frame: CGRectMake(3, 5, 50, 20))
    label.font = UIFont(name: "Arial-BoldMT", size: 16)
    label.text = "title"
    label.textAlignment = .Center
    label.textColor = UIColor.whiteColor()
    label.backgroundColor =   UIColor.clearColor()
    button.addSubview(label)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton

허용되는 답변의 문제는 UIBarButtonItem강조 표시 될 때 텍스트가 변경되지 않는다는 것입니다. 아래 코드는 텍스트와 이미지를 표시합니다. UIEdgeInsetsMake이동 왼쪽에있는 텍스트와 오른쪽에있는 이미지입니다.

UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(myButtonEvent:) 
             forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 32)];

[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] 
                 forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] 
                 forState:UIControlStateHighlighted];
button.titleEdgeInsets = UIEdgeInsetsMake(-2, -20, 2, 20);
button.titleLabel.font = font;
button.titleLabel.textAlignment = NSTextAlignmentLeft;

UIImage *image = [UIImage imageNamed:@"imageName"];
[button setImage:image 
        forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32);
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];

UIBarButtonItem 내에서 UIButton을 사용자 정의보기로 사용. 당신이 원하는 그러나 당신은 사용, 이미지 및 텍스트를 포함한있는 UIButton을 만들 수 있습니다 -setImage:forState:-setTitle:forState:

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[button setTitle:@"Settings" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButtonItem;

이것은 UIButton을 네비게이션 바의 왼쪽 바 버튼 슬롯으로 드래그하는 것만으로 인터페이스 빌더를 사용하여 수행 할 수 있습니다.


여기에 일반 uibarbuttonitem에 대한 색조 및 이미지 simmilar를 처리하는 답변을 게시했습니다 ... https://stackoverflow.com/a/28348461/925135


NSAttributedString을 사용한 또 다른 접근 방식 :

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Button Text"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"buttonImage"];
textAttachment.bounds = CGRectMake(0, -3, textAttachment.image.size.width, textAttachment.image.size.height); //the origin y value depends on the size of the image to get a perfect fit
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attrStringWithImage]; // Adding the image at the beginning
[customButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[customButton sizeToFit];
[customButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:customButton];

UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImage *backgroundSelected = [UIImage imageNamed:@"icon_selected.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(ButtonTapped:event:)forControlEvents:UIControlEventTouchUpInside]; //adding action
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setBackgroundImage:backgroundSelected forState:UIControlStateSelected];
button.frame = CGRectMake(0 ,0,35,35);

그런 다음 해당 버튼을 사용자 지정 바 버튼으로

UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView : button];
self.navigationItem.leftBarButtonItem = barButton;

이것은 Swift 3에 대한 ripegooseberry의 답변 업데이트 버전입니다.

    let button =  UIButton(type: .custom)
    button.setImage(UIImage(named: "icon_right"), for: .normal)
    button.addTarget(self, action: Selector(("buttonAction")), for: .touchUpInside)
    button.frame = CGRect(x: 0, y: 0, width: 53, height: 31)
    button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
    let label = UILabel(frame: CGRect(x: 3, y: 5, width: 50, height: 20))
    label.font = UIFont(name: "Arial-BoldMT", size: 16)
    label.text = "title"
    label.textAlignment = .center
    label.textColor = UIColor.white
    label.backgroundColor =   UIColor.clear
    button.addSubview(label)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton

굉장한 솔루션! UIToolbar에 UISlider를 추가하려고했는데 이렇게했습니다! 다음을 통해 사용자 정의 버튼에 대한 대상 작업을 추가하는 것을 잊지 마십시오.

  customButton.targetForAction(#selector(addTapped), withSender: self)

이렇게하면 버튼을 제어 할 수 있습니다. :)


다음은 이전 답변을 기반으로 한 내 솔루션입니다. 도움이 될 수 있습니다.

extension UIBarButtonItem {
    static func button(image: UIImage, title: String, target: Any, action: Selector) -> UIBarButtonItem {
        let button = UIButton()
        button.setImage(image, for: .normal)
        button.addTarget(target, action: action, for: .touchUpInside)
        button.setTitle(title, for: .normal)
        button.sizeToFit()
        return UIBarButtonItem(customView: button)
    }
}

참고 URL : https://stackoverflow.com/questions/18844681/how-to-make-custom-uibarbuttonitem-with-image-and-label

반응형