点击后更改UIButton的文本或背景

点击后更改UIButton的文本或背景

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

问题描述

我尝试更改3个按钮的外观(TitleLable +背景)和TextView的文本,具体取决于单击3个按钮之一的情况. (类似于标签式内容)

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的文本可以很好地更改,但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的文本或背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:15