我正在尝试将图标从UIBarButtonSystemItem like UIBarButtonSystemItem.Camera类型转换为UIImage。 用户可以在Swift and ObjC中做到这一点,但我无法弄清楚。
按照Swift&ObjC教程中的说明进行操作时,我的代码中出现空引用异常错误
{
UIImage image = null;
viewController.InvokeOnMainThread(() =>
{
UIBarButtonItem oldItem = viewController.NavigationItem.RightBarButtonItem;
var buttonItem = new UIBarButtonItem(item);
// Add to toolbar and render it
viewController.NavigationItem.RightBarButtonItem = buttonItem;
var x = new ObjCRuntime.Selector("view");
var y = viewController.NavigationItem.RightBarButtonItem.PerformSelector(x);
UIView itemView = (UIView)y;
// Get the image from real UIButton
foreach (var view in itemView.Subviews)
{
if (view.GetType() == typeof(UIButton))
image = ((UIButton)view).ImageView.Image;
}
viewController.NavigationItem.RightBarButtonItem = oldItem;
});
return image;
}
我也尝试过这个
public static UIImage ToUIImage2(UIBarButtonSystemItem item, UIViewController viewController)
{
UIImage image = null;
viewController.InvokeOnMainThread(() =>
{
var buttonItem = new UIBarButtonItem(item);
// Add to toolbar and render it
var tempItem = new UIBarButtonItem[1] { buttonItem };
var bar = new UIToolbar();
bar.SetItems(tempItem, false);
bar.SnapshotView(true);
// Get the image from real UIButton
var buttonItemView = bar.ValueForKey(new Foundation.NSString("view"));
var itemView = (UIView)buttonItemView;
foreach (var view in itemView.Subviews)
{
if (view.GetType() == typeof(UIButton))
image = ((UIButton)view).ImageView.Image;
}
});
return image;
}
在StackOverflow中找不到C#的任何内容。 有人尝试过吗?
答案 0 :(得分:0)
public extern static IntPtr IntPtr_objc_msgSend (IntPtr receiver, IntPtr selector);
public static UIImage GetImage (UIBarButtonSystemItem systemItem)
{
var tempItem = new UIBarButtonItem (systemItem);
// Add to toolbar and render it
var bar = new UIToolbar ();
bar.SetItems (new [] { tempItem }, false);
bar.SnapshotView (true);
// Get image from real UIButton
var selHandle = Selector.GetHandle ("view");
var itemView = Runtime.GetNSObject<UIView> (IntPtr_objc_msgSend (tempItem.Handle, selHandle));
foreach (var view in itemView?.Subviews) {
if (view is UIButton button)
return button.ImageForState (UIControlState.Normal);
}
return null;
}
DaleXSoto提供的解决方案
“问题是您正在向tempItem对象调用选择器(视图) 但这是一个骇客,因为UIBarButtonItem响应查看只是因为有人发现了,但是它不在标题上
因此,执行IntPtr_objc_msgSend是调用tempItem对象上的视图的方式”