iOS 15 的新 ConfigurationUpdateHandler 用于 Objective-C 中的 UIButton 的示例
Example for using iOS 15's new ConfigurationUpdateHandler for a UIButton in Objective-C
我想试用 iOS15 中提供的新 UIButtonConfigurationUpdateHandler 来创建切换按钮。有很多非常好的示例使用 Swift(like this one by Sarunw,但我的大部分代码库是 Objective-C。有人可以提供有关如何为我动态配置按钮的示例代码吗?谢谢!
也许这会让你上路...
#import <UIKit/UIKit.h>
@interface BtnCfgViewController : UIViewController
{
BOOL bIsOn;
}
@end
@implementation BtnCfgViewController
- (void)viewDidLoad {
[super viewDidLoad];
bIsOn = NO;
if (@available(iOS 15.0, *)) {
UIAction *tapAction = [UIAction actionWithHandler:^(UIAction* action){
self->bIsOn = !self->bIsOn;
}];
UIButtonConfiguration *cfg = [UIButtonConfiguration plainButtonConfiguration];
UIButton *myButton = [UIButton buttonWithConfiguration:cfg
primaryAction:tapAction];
myButton.configurationUpdateHandler = ^(UIButton *btn) {
UIButtonConfiguration *cfg = btn.configuration;
NSString *s = [NSString stringWithFormat:@"Toggle: %@", self->bIsOn ? @"☑︎" : @"☐"];
cfg.title = s;
btn.configuration = cfg;
};
myButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:myButton];
UILayoutGuide *g = [self.view safeAreaLayoutGuide];
[NSLayoutConstraint activateConstraints:@[
[myButton.topAnchor constraintEqualToAnchor:g.topAnchor constant:20.0],
[myButton.widthAnchor constraintEqualToConstant:200.0],
[myButton.heightAnchor constraintEqualToConstant:60.0],
[myButton.centerXAnchor constraintEqualToAnchor:g.centerXAnchor],
]];
}
}
我想试用 iOS15 中提供的新 UIButtonConfigurationUpdateHandler 来创建切换按钮。有很多非常好的示例使用 Swift(like this one by Sarunw,但我的大部分代码库是 Objective-C。有人可以提供有关如何为我动态配置按钮的示例代码吗?谢谢!
也许这会让你上路...
#import <UIKit/UIKit.h>
@interface BtnCfgViewController : UIViewController
{
BOOL bIsOn;
}
@end
@implementation BtnCfgViewController
- (void)viewDidLoad {
[super viewDidLoad];
bIsOn = NO;
if (@available(iOS 15.0, *)) {
UIAction *tapAction = [UIAction actionWithHandler:^(UIAction* action){
self->bIsOn = !self->bIsOn;
}];
UIButtonConfiguration *cfg = [UIButtonConfiguration plainButtonConfiguration];
UIButton *myButton = [UIButton buttonWithConfiguration:cfg
primaryAction:tapAction];
myButton.configurationUpdateHandler = ^(UIButton *btn) {
UIButtonConfiguration *cfg = btn.configuration;
NSString *s = [NSString stringWithFormat:@"Toggle: %@", self->bIsOn ? @"☑︎" : @"☐"];
cfg.title = s;
btn.configuration = cfg;
};
myButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:myButton];
UILayoutGuide *g = [self.view safeAreaLayoutGuide];
[NSLayoutConstraint activateConstraints:@[
[myButton.topAnchor constraintEqualToAnchor:g.topAnchor constant:20.0],
[myButton.widthAnchor constraintEqualToConstant:200.0],
[myButton.heightAnchor constraintEqualToConstant:60.0],
[myButton.centerXAnchor constraintEqualToAnchor:g.centerXAnchor],
]];
}
}