web-dev-qa-db-ja.com

画像とラベルでカスタムUIBarButtonItemを作成する方法は?

次のような画像とテキストの両方を含むカスタムUIBarButtonItemを作成したいと思います。

enter image description here

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;

しかし、これを使用すると、画像のみが取得され、ラベルは取得されません。私は何を間違えていますか?

62
Dvole
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;
101
karthika

UIBarButtonItemにカスタムビューを追加できます。

IOS 7には、UIButtonTypeSystemと呼ばれるUIButtonという新しいbuttonTypeがあり、これが目的に役立ちます。これを試して、

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
22
ramgandhi

BarButtonItemがStoryboardにある場合、別のButtonをBarButtonItemにドラッグできます。したがって、BarButtonItem内にButtonがあります。ボタンに画像とラベルの両方を追加できます。

14
Xin Wang

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
12
drpawelo

受け入れられた回答の問題は、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];
4
bbarnhart

UIBarButtonItem内でカスタムビューとしてUIButtonを使用します。 -setImage:forState:-setTitle:forState:を使用して、画像とテキストを含め、必要に応じてUIButtonを作成できます

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;

これは、UIBuilderをナビゲーションバーの左バーボタンスロットにドラッグするだけで、インターフェイスビルダーを使用して実行できます。

4
silentBeep

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];
3
Gabriel Candia

私はここで通常のuibarbuttonitemと同様の色合いと画像を処理する答えを投稿しました... https://stackoverflow.com/a/28348461/925135

3
Renetik

これは、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
2
JipZipJib
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);

次に、そのボタンをカスタムbarbuttonとして作成します

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

素晴らしい解決策!私はUIToolbarにUISliderを追加したいと考えていました。カスタムボタンのターゲットアクションを追加することを忘れないでください:

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

このようにして、ボタンを制御できます:)

1
Agustin

これまでの回答に基づいた私の解決策があります。役に立つかもしれません。

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