gpt4 book ai didi

ios - 为加载的 .xib 分配属性

转载 作者:行者123 更新时间:2023-11-29 02:04:49 26 4
gpt4 key购买 nike

我正在尝试更改正在加载的 .xib 中按钮的标题:

CustomToolBar *toolBar = (CustomToolBar *)[[[[NSBundle mainBundle] 
loadNibNamed:@"CoolBar"
owner:self options:nil] objectAtIndex:0]
initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 70)];

我试过直接使用

toolBar.button.titleLabel.text = @"VALUE";

并且通过一个自定义的setter方法,

- (void)updateButtonText:(NSString *)buttonText {
_button.titleLabel.text = buttonText;
}

但是,它始终默认为 .xib 文件中给定的值。

最佳答案

CustomToolBar *toolBar = 
(CustomToolBar *)[[[[NSBundle mainBundle]
loadNibNamed:@"CoolBar"
owner:self options:nil] objectAtIndex:0]
initWithFrame:CGRectMake(
0, self.view.frame.size.height, self.view.frame.size.width, 70)];

您的代码毫无意义。您不能/不得init从 Nib 加载的对象;它已经被初始化了。

我建议您将该语句分成几个步骤,并确保每个步骤都能提供您期望的结果 - 当然,并放弃 init

NSArray* arr = [NSBundle mainBundle] 
loadNibNamed:@"CoolBar"
owner:nil options:nil]; // did it load?
id obj = [arr objectAtIndex: 0]; // did you get the CustomToolbar?
CustomToolBar *toolBar =
(CustomToolBar *) obj; // still ok?
toolbar.frame = CGRectMake(
0, self.view.frame.size.height, self.view.frame.size.width, 70);

等等。

然后您就可以开始考虑您想要使用 toolBar做什么。目前它还没有被放入您的界面中,因此您无法知道您的更改是否会影响它。一旦完成,您就可以开始询问自己代码的其余部分。例如,尝试直接设置 UIButton 的 titleLabel.text 是疯狂的(也是错误的);这不是按钮的工作方式。一旦你有了toolBar,你就可以说

[toolBar.button setTitle:@"VALUE" forState: UIControlStateNormal];

关于ios - 为加载的 .xib 分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com