我想在工具栏 (UIToolbar
) 上显示一个标签 (UILabel
和一个 ImageView (UIImageView
)。在 Interface Builder 中,我为每个 View 添加了一个条形按钮项 (UIBarButtonItem
),并在每个条形按钮项上拖了一个空 View (UIView
)。请参阅下面是 View 层次结构的屏幕截图。
我假设这些 View 中的每一个都变成了customViews
,我应该能够在代码中访问它
UIView *labelBarButtonView = (UIView*)labelBarButtonItem.customView;
然后使用
访问标签或 ImageViewUILabel *companyLabel = (UILabel*)[labelBarButtonItem.customView viewWithTag:tag];
但是,在运行代码时,我的应用程序崩溃并显示错误消息:'NSInvalidArgumentException',原因:'-[UIView customView]:无法识别的选择器发送到实例
。
我错过了什么?在 Interface Builder 中创建 View 并在代码中访问它们的属性的更好方法是什么?
谢谢!
最佳答案
好的,我认为这是您的问题。在代码行中:
UIView *labelBarButtonView = (UIView*)labelBarButtonItem.customView;
您实际上是将 labelBarButtonItem
转换为 UIView
,然后从中请求 customView
。看起来你会转换 customView
但你不是。所以尝试使用这段代码:
UIView *labelBarButtonView = (UIView*)((UIBarButtonItem *)labelBarButtonItem.customView);
上面的代码转换 labelBarButtonItem
拉出 customView
然后转换它。然后要获取标签,您可以通过以下方式访问它:
UILabel *companyLabel = (UILabel*)[labelBarButtonView viewWithTag:tag];
关于ios - 如何将标签和 ImageView 添加到工具栏并在代码中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729341/