ios - 方法不改变变量的值

标签 ios objective-c

首先,对于这个问题,我很抱歉,但我是 iOS 开发的新手,整个下午我都被困在这个问题上,我试图使用位于另一个 viewController 中的一个 slider 更改 int 变量的值。

行的 slider 位于 View 内的模态窗口中,我认为这是问题所在,但我不知道。

这是代码:

@interface ViewController ()
  @property int row, column, actualGame;
@end

- (IBAction)rowChanged:(id)sender {
    UISlider *slider = (UISlider *)sender;
    int val = slider.value;
    [self setRow: val];
    self.rowLabel.text = [NSString stringWithFormat:@"%d",val];
} 

- (IBAction)columnChanged:(id)sender {
    UISlider *slider = (UISlider *)sender;
    int val = slider.value;
    _column = val;
    self.collumLabel.text = [NSString stringWithFormat:@"%d",val];
}

最佳答案

为了在 View Controller 之间传递数据,有几个不同的选项可供您使用。最简单的方法是在第二个 View Controller 上存储对第一个 View Controller 的引用。您可以在第一个 View Controller 的“prepareForSegue”方法中设置该属性。

FirstViewController.h(呈现模态 VC 的 View Controller ):

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController

@property (nonatomic) float sliderValue;

@end

FirstViewController.m

#import "FirstViewController.h"
#import "ViewController.h"

@implementation FirstViewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"mySegueDefinedInStoryboard"]) {
        ViewController *destinationViewController = (ViewController *)segue.destinationViewController;
        destinationViewController.firstViewController = self;
    }
}

@end

ViewController.h(模态视图 Controller ):

#import <UIKit/UIKit.h>

@class FirstViewController;

@interface ViewController : UITableViewController

@property (nonatomic, weak) FirstViewController *firstViewController;

@end

ViewController.m

#import "ViewController.h"
#import "FirstViewController.h"

@implementation ViewController

- (IBAction)columnChanged:(UISlider *)sender {
    float value = sender.value;
    self.firstViewController.sliderValue = value;
}

@end

此方法的缺点是它会创建紧密耦合的代码 - ViewController 需要了解 FirstViewController,这不是最佳选择。一旦您多练习一些,您将了解如何创建自己的委托(delegate),这样您就可以将消息发送到其他 View Controller ,而无需关心它们的类是什么或它们的属性是什么。

Apple Documentation on the Delegate Pattern

关于ios - 方法不改变变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27153901/

相关文章:

ios - 无法在启动屏幕上显示某些图像

ios - NSUserDefault 中的 NSMutableArray,检索 NULL

android - 长按时 flutter 触觉反馈

ios - ios 的 Pwinty api

ios - 根据键的值从 NSDictionary 的 NSMutableArray 中删除重复项

objective-c - presentViewController : crash on iOS <6 (AutoLayout)

iOS导航没有导航项

ios - 为什么当我对 int 使用 #define 时需要将它们括在括号中?

ios - 如何在XCode的自适应自动布局中为相同大小的类声明不同的字体大小?

iphone - 如何检查 NSString 是否包含 '%'?