Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect实例分析

时间:2022-08-24 08:58:51

本文以实例详细描述了Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect的定义及用法,具体如下所示:

1、NSRange:

NSRange的原型为

?
1
2
3
4
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;

NSMakeRange的函数:

NS_INLINEz是内联函数

?
1
2
3
4
5
6
7
8
typedef NSRange *NSRangePointer;
 
NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
NSRange r;
r.location = loc;
r.length = len;
return r;
}

使用方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//NSRange表示的是范围
NSRange range;
range.location = 18;
range.length = 34;
 
NSLog(@"location is %zi",range.location);
NSLog(@"length is %zi",range.length);
 
//快速创建
range = NSMakeRange(8, 10);
NSLog(@"location is %zi",range.location);
NSLog(@"length is %zi",range.length);
 
//NSStringFromRange将上面的结构体转化成字符串类型,打印出来
 
NSString* str1 = NSStringFromRange(range);
 
//%@是一个OC对象,range代表的是一个结构体,str是一个OC对象
NSLog(@"rang is %@",str1);

2、NSPoint:

NSPoint的原型:

?
1
2
3
4
struct CGPoint {
CGFloat x;
CGFloat y;
};

NSMakePoint函数:

?
1
2
3
4
5
6
NS_INLINE NSPoint NSMakePoint(CGFloat x, CGFloat y) {
NSPoint p;
p.x = x;
p.y = y;
return p;
}

CGPointMake函数:

?
1
2
3
4
CGPointMake(CGFloat x, CGFloat y)
{
CGPoint p; p.x = x; p.y = y; return p;
}

使用方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//NSPoint指的是位置
NSPoint point;
 
//给结构体里面的点进行赋值
point.x = 10;
point.y = 10;
 
//快速创建点
point = NSMakePoint(10, 18);
 
//常见的是CGPointMake创建点的函数
point = CGPointMake(29, 78);
NSString* str2 = NSStringFromPoint(point);
NSLog(@"point is %@",str2);

3、CGSize:

CGSize的原型:

?
1
2
3
4
struct CGSize {
CGFloat width;
CGFloat height;
};

NSMakeSize函数:

?
1
2
3
4
5
6
NS_INLINE NSSize NSMakeSize(CGFloat w, CGFloat h) {
NSSize s;
s.width = w;
s.height = h;
return s;
}

CGSizeMake函数:

?
1
2
3
4
CGSizeMake(CGFloat width, CGFloat height)
{
CGSize size; size.width = width; size.height = height; return size;
}

使用方法:

?
1
2
3
4
5
6
7
8
9
NSSize size;
  
size.width = 100;
size.height = 12;
size = NSMakeSize(12, 12);
size = CGSizeMake(11, 11);
 
NSString* str3 = NSStringFromSize(size);
NSLog(@"%@",str3);

4、CGRect:

CGRect的原型:

?
1
2
3
4
struct CGRect {
CGPoint origin;
CGSize size;
};

CGRectMake的函数:

?
1
2
3
4
5
6
7
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}

NSMakeRect函数:

?
1
2
3
4
5
6
7
8
NS_INLINE NSRect NSMakeRect(CGFloat x, CGFloat y, CGFloat w, CGFloat h) {
NSRect r;
r.origin.x = x;
r.origin.y = y;
r.size.width = w;
r.size.height = h;
return r;
}

使用方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//既包含了尺寸大小和位置
NSRect rect;
rect.origin.x = 12;
rect.origin.y = 14;
rect.size.width = 12;
rect.size.height = 15;
 
//快速创建方法
rect = CGRectMake(12, 12, 12, 12);
rect = NSMakeRect(11, 11, 11, 11);
 
//转化成字符串打印出来
NSString* str5 = NSStringFromRect(rect);
NSLog(@"rect is <a href="mailto:%@",str5" rel="external nofollow">%@",str5</a>);