点击后更改 UIButton 的文本或背景 [英] Change Text or Background of UIButton after a tap

查看:14
本文介绍了点击后更改 UIButton 的文本或背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据单击 3 个按钮之一来更改 TextView 的 3 个按钮的外观(TitleLable + 背景)和文本.(类似于选项卡式内容)

I try to change the the Look of 3 Buttons (TitleLable + Background) and Text of a TextView in dependents of the click on one of the 3 Buttons. (Something like Tabbed Content)

我在 xib 中创建了 4 个元素,并将它们与 .h 链接:

I 've created the 4 elements in the xib, and linked them with the .h:

   IBOutlet UIButton *buttonTab1;
    IBOutlet UIButton *buttonTab2;
    IBOutlet UIButton *buttonTab3;

    IBOutlet UITextView *thisDescription;

    - (IBAction)showTab1:(id)sender;
    - (IBAction)showTab2:(id)sender;
    - (IBAction)showTab3:(id)sender;

@property (strong, nonatomic) IBOutlet UIButton *buttonTab1;
@property (strong, nonatomic) IBOutlet UIButton *buttonTab2;
@property (strong, nonatomic) IBOutlet UIButton *buttonTab3;

在 .m 处,我尝试更改 4 个元素(此处为按钮 1 的代码):

at the .m i try to change the 4 Elements (here the code for Button 1):

@synthesize buttonTab1, buttonTab2, buttonTab3;

- (IBAction)showTab1:(id)sender{
        thisDescription.text = [NSString stringWithFormat:@"INHALT TAB 1: %@",transferDescription];
        buttonTab1.imageView.image = [UIImage imageNamed:@"content_tab1_on.png"];
        buttonTab2.imageView.image = [UIImage imageNamed:@"content_tab2.png"];
        buttonTab3.imageView.image = [UIImage imageNamed:@"content_tab3.png"];
        buttonTab1.titleLabel.text = @"Tab1on";
        buttonTab2.titleLabel.text = @"Tab2";
        buttonTab3.titleLabel.text = @"Tab3";
    }

TextViewElement 的 Text 变化很好,但 Title &背景与xib中的一样.

The Text of the TextViewElement changes fine, but the Title & the Background is the same like in the xib.

推荐答案

要在按钮上设置背景图片和标题,您应该使用 setTitle:forState: 方法和setBackgroundImage:forState: 方法.由于按钮可能根据状态有不同的标题或背景,因此直接设置图像或标签将不起作用.

To set background image and title on buttons you should use the setTitle:forState: methods and setBackgroundImage:forState: methods. Since button may have a different title or background depending on the state, settings the image or label directly will not work.

这应该让您了解如何在您的代码中实现这一点:

This should give you some idea on how to implement this in you code:

[buttonTab1 setBackgroundImage:[UIImage imageNamed:@"content_tab1_on.png"] forState:UIControlStateNormal];
[buttonTab2 setBackgroundImage:[UIImage imageNamed:@"content_tab2.png"] forState:UIControlStateNormal];
[buttonTab3 setBackgroundImage:[UIImage imageNamed:@"content_tab3.png"] forState:UIControlStateNormal];
[buttonTab1 setTitle:@"Tab1on" forState:UIControlStateNormal];
[buttonTab2 setTitle:@"Tab2" forState:UIControlStateNormal];
[buttonTab3 setTitle:@"Tab3" forState:UIControlStateNormal];

这篇关于点击后更改 UIButton 的文本或背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆