博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在Swift里用UnsafeMutablePointer
阅读量:6951 次
发布时间:2019-06-27

本文共 1848 字,大约阅读时间需要 6 分钟。

下午在适配iPadUI的时候,用到了UIPopoverPresentationController,然后在转屏的时候需要调用UIPopoverPresentationControllerDelegate来返回一个适配后的view和CGRect,这里先看下在OC里的写法:

- (void)popoverPresentationController: (nonnull UIPopoverPresentationController *) popoverPresentationController willRepositionPopoverToRect:(inout nonnull CGRect *)rect inView:(inout UIView *__autoreleasing __nonnull * __nonnull)view { *view = self.someView; *rect = self.someView.bounds; }

在OC里面你可以很方便的修改这里的参数值来返回正确的指针地址,但是在swift里面方法是这样子的:

func popoverPresentationController( popoverPresentationController:UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer
, inView view: AutoreleasingUnsafeMutablePointer
) { // What to do here? }

UnsafeMutablePointer和AutoreleasingUnsafeMutablePointer是什么鬼?这俩玩意要怎么返回值给他们?

先说结论
   在Swift里面rect.memory就是Objective-C里面的*rect

原因:

  这两个参数并不是swift本身的写法混乱,而是为了让swift和Cocoa和UIKit下的Objective-C和C的frameworks 相互转换兼容,查阅apple的SDK你可以发现UnsafeMutablePointer就是一个结构体:

struct UnsafeMutablePointer

你可以把它看成一个Memory的指针,那现在再来看protocol里面的两个参数:

  • UnsafeMutablePointer<CGRect>是一个CGRect的指针
  • AutoreleasingUnsafeMutablePointer<UIView?>是一个可选View的指针

所以这里你可以通过它的memory属性来访问它的引用存储值:

/// Access the underlying raw memory, getting and setting values.public var memory: Memory { get nonmutating set }

例如:

// Objective-C assuming CGRect *rect;CGRect oldRect = *rect;*rect = newRect;// Swift assuming rect: UnsafeMutablePointer
oldRect = rect.memory rect.memory = newRect

简单来说:在Swift里面rect.memory就是Objective-C里面的*rect

所以最后我们可以在Swift里面这么写:

func popoverPresentationController( popoverPresentationController:UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer
, inView view: AutoreleasingUnsafeMutablePointer
) { view.memory = someView rect.memory = someView.bounds }

参考:

转载地址:http://syuil.baihongyu.com/

你可能感兴趣的文章
迁移Gitolite仓库到GitLab(一)
查看>>
设计模式学习与应用——单例模式
查看>>
Algorithms - Counter计数器 的 详解 与 代码
查看>>
Android - Android Studio 自动(auto)添加import 语句
查看>>
删除exchange误发邮件
查看>>
我的友情链接
查看>>
关于android输入框被键盘遮挡的问题
查看>>
Linux 怎么shell脚本定时备份mysql数据库
查看>>
常用颜色代码
查看>>
我的友情链接
查看>>
openstack相关资料集结
查看>>
初学SQL
查看>>
MyBatis多参数传递之默认命名方式示例——MyBatis学习笔记之十二
查看>>
一道面试题,设计电路,set,reset
查看>>
使用dialog插件弹出提示和确定信息对话框8-8
查看>>
Hibernate4实战 之 第五部分:Hibernate的事务和并发
查看>>
弎问笔录30 之 狐狸和兔子(二)
查看>>
VBOX下安装RHEL5.4增强工具失败的解决办法
查看>>
php.ini配置文件
查看>>
运维自动化之zabbix(添加Graph screen)(3)
查看>>