oc中属性前加下划线
时间: 2024-02-16 09:00:49 浏览: 21
在Objective-C中,属性前加下划线 `_` 是一种常见的命名约定,用于表示属性的实例变量。实例变量是属性的具体实现方式,它们存储了对象的状态和数据,而属性则提供了一种简洁的方式来访问这些实例变量。
以一个例子来说明,如果我们有一个`Person`类,包含`name`和`age`两个属性:
```
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
```
在实现类中,我们可以使用下划线 `_` 来表示属性的实例变量:
```
@implementation Person {
NSString *_name;
NSInteger _age;
}
@end
```
在上面的例子中,我们在`@implementation`中定义了`_name`和`_age`两个实例变量,用于存储`name`和`age`两个属性的值。
需要注意的是,使用下划线 `_` 表示属性的实例变量不是必须的,也不是语言本身的要求,而是一种编码风格和约定。此外,属性的实例变量应该在`@implementation`中定义,而不是在`@interface`中,这样可以避免将实例变量暴露给外部访问。
相关问题
OC 的 NSMutableParagraphStyle 属性介绍
NSMutableParagraphStyle 是 NSMutableAttributedString 的一种子类,用于描述富文本中的段落样式。它可以控制段落的对齐方式、行间距、段落间距、首行缩进等属性。下面是 NSMutableParagraphStyle 常用的一些属性:
1. alignment:控制文本对齐方式,可选值为 NSTextAlignmentLeft、NSTextAlignmentCenter、NSTextAlignmentRight、NSTextAlignmentJustified 和 NSTextAlignmentNatural。
2. lineSpacing:控制行间距,可以是任意正数。
3. paragraphSpacing:控制段落间距,可以是任意正数。
4. firstLineHeadIndent:控制首行缩进,可以是任意正数或负数。
5. headIndent:控制除首行外的缩进,可以是任意正数或负数。
6. tailIndent:控制文本的尾部缩进,可以是任意正数或负数。
7. lineBreakMode:控制文本换行模式,可选值为 NSLineBreakByWordWrapping、NSLineBreakByCharWrapping、NSLineBreakByClipping 和 NSLineBreakByTruncatingTail。
8. baseWritingDirection:控制文本的书写方向,可选值为 NSWritingDirectionNatural、NSWritingDirectionLeftToRight 和 NSWritingDirectionRightToLeft。
通过设置这些属性,可以实现各种不同的段落样式,从而满足不同的排版需求。
OC中 自定义cell
在 OC 中,我们可以通过继承 UITableViewCell 类来自定义 UITableViewCell。具体步骤如下:
1. 创建一个继承自 UITableViewCell 的类,例如 MyCustomCell。
2. 在 MyCustomCell.h 文件中声明需要自定义的视图属性,例如:
```
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *titleLabel;
```
3. 在 MyCustomCell.m 文件中实现自定义的视图布局,例如:
```
- (void)layoutSubviews {
[super layoutSubviews];
self.iconImageView.frame = CGRectMake(10, 10, 50, 50);
self.titleLabel.frame = CGRectMake(70, 20, 200, 30);
[self.contentView addSubview:self.iconImageView];
[self.contentView addSubview:self.titleLabel];
}
```
4. 在使用该自定义 cell 的 UITableView 的代理方法中,使用 MyCustomCell 类来创建 cell,例如:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCell"];
if (!cell) {
cell = [[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCustomCell"];
}
cell.iconImageView.image = [UIImage imageNamed:@"icon"];
cell.titleLabel.text = @"这是一个自定义 cell";
return cell;
}
```
这样就可以使用自定义 cell 来展示 UITableView 中的数据了。