为什么我更改segmentedControl索引标签不会改变?

时间:2014-11-27 23:51:47

标签: objective-c xcode uilabel uisegmentedcontrol

您好我正在尝试更改分段控件时更改标签文本。

以下是代码:

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize segmentedControl;
@synthesize distTf;
@synthesize weightLabel;
@synthesize spaceLabel;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


if(segmentedControl.selectedSegmentIndex==0) {

    weightLabel.text = @"Yards";
    spaceLabel.text = @"Pounds";

} else if(segmentedControl.selectedSegmentIndex==1){

    weightLabel.text = @"Meters";
    spaceLabel.text = @"Kilograms";

}

}

- (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}

@end

当index = 0时它开始很好但如果我选择index = 1则不会改变。你能看到我能做什么吗?

全部谢谢

2 个答案:

答案 0 :(得分:1)

是。我们可以看到,在加载视图时,您只需执行一次更改标签的代码即可。实际上,您没有将代码绑定到分段控件中的更改。

此代码:

if(segmentedControl.selectedSegmentIndex==0) {

    weightLabel.text = @"Yards";
    spaceLabel.text = @"Pounds";

} else if(segmentedControl.selectedSegmentIndex==1){

    weightLabel.text = @"Meters";
    spaceLabel.text = @"Kilograms";

}

应该放在分段控制的变更值处理程序中。

答案 1 :(得分:1)

将UISegment控件连接到动作事件“valuechanged”,并在用户更改其选择时为更改标签文本编写以下方法。

- (IBAction)segment_Changed:(id)sender{

UISegmentedControl * segment = (UISegmentedControl *)sender;

if(segment.selectedSegmentIndex == 0){

    weightLabel.text = @"Yards";
    spaceLabel.text = @"Pounds";

}else if (segment.selectedSegmentIndex == 1){

    weightLabel.text = @"Meters";
    spaceLabel.text = @"Kilograms";
}}