ios - 在 Xcode 中连接开关时出现问题?

标签 ios xcode uiviewcontroller

我在连接交换机时遇到问题。我了解如何将开关连接为 socket 并让它有操作更改值的 bool 状态,但我需要开关在不同的 View Controller 中执行操作。

情况是这样的:我有一个主 TableView Controller ,称为 View Controller A。我有第二个 View Controller ,我们称之为 View Controller B,它控制菜单边栏(在常规 View Controller 上,而不是 TableView ) 由条形项触发。我希望能够打开菜单,点击侧边栏中的开关,并在由 View Controller A 控制的主 TableView 中进行一些更改。

有什么办法可以做到这一点吗?我似乎无法从 B 访问或更改 View Controller A 中的 IBOutlets。有没有办法让 B 中的操作与开关链接更改值的 bool 状态,并在 Controller 中等待操作一个会响应 bool 值变化的?我不确定如何解决这个问题。感谢帮助!

最佳答案

你应该使用 delegation pattern .您将在 Controller A 中等待一个 Action ,但不是响应 B 中更改的值,该 Action 将在适当的时候由 B 触发

ViewControllerB.h

// Create delegate protocol and property
@protocol ViewControllerBDelegate <NSObject>
    - (void)switchPressed:(BOOL)switchStatus;
@end

@interface ViewControllerB : NSObject
    @property (nonatomic,weak) id<ViewControllerBDelegate> delegate;
@end

ViewControllerB.m

// When switch is tapped, call delegate method if it is implemented by delegate object
- (IBAction)flip: (id) sender {
    UISwitch *onoff = (UISwitch *) sender;
    if ([self.delegate respondsToSelector:@selector(switchPressed:)]) {
        [self.delegate switchPressed:onoff.on];
    }
}

ViewControllerA.h

// Conform to ViewControllerB protocol
#import ViewControllerB.h

@interface ViewControllerA : NSObject,ViewControllerBDelegate

ViewControllerA.m

// Set self (VC A) as VC B's delegate
- (void)ViewDidLoadOrSomeOtherFunction {    
    ViewControllerB *vcB = [[ViewControllerB alloc] init];
    vcB setDelegate = self;
}

// Implement delegate method
- (void)switchPressed:(BOOL)switchStatus {
    if (switchStatus) {
        // Make changes on VC A
    }
}

关于ios - 在 Xcode 中连接开关时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38412427/

相关文章:

ios - 使用 Rest API Swift 3

Android/iOS OpenCV 扩眼检测

iOS 11 - 如何读取/解析来自 CoreNFC 的 NDEF 消息?

iphone - 无法在 Xcode 4.5 中安装 iOS 5.1 模拟器

ios - 使用 UIModalTransitionStylePartialCurl 时如何在 presentModalViewController 后面更新?

ios - 路径应用程序时间轴实现

ios - 点击 tabBar 项目应该总是打开第一个 View Controller

swift - Xcode Swift Firebase 如何创建 FIRAuth 的第二个实例

ios - 推然后模态然后推?

ios - swift 崩溃 : function signature specialization <Arg[0] = Owned To Guaranteed>