提问人:Brent 提问时间:2/19/2022 更新时间:2/20/2022 访问量:842
在 Objective-C 中将 iOS 15 的新 ConfigurationUpdateHandler 用于 UIButton 的示例
Example for using iOS 15's new ConfigurationUpdateHandler for a UIButton in Objective-C
问:
我想尝试使用 iOS 15 中提供的新 UIButtonConfigurationUpdateHandler 来创建切换按钮。有很多使用 Swift 的非常好的示例(比如 Sarunw 的这个示例,但我的大部分代码库都是 Objective-C。有人可以提供有关如何为我动态配置按钮的示例代码吗?谢谢!
答:
2赞
DonMag
2/20/2022
#1
也许这会让你上路......
#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],
]];
}
}
评论
1赞
Brent
2/20/2022
谢谢!这正是我需要的......对不起,如果我不清楚。最后,这条线是我错过的。btn.configuration = cfg;
评论