【问题标题】:Setting firstLineHeadIndent in UITextView attributedText在 UITextView 属性文本中设置 firstLineHeadIndent
【发布时间】:2015-01-04 02:59:28
【问题描述】:

当您键入时,我正在缩进 UITextView 中的第一行。这是一个演示。

这可行,但我不知道如何让文本视图在出现时缩进。如果您从键盘添加和删除一个字符,它会正确缩进空行,但当它第一次出现时我不知道如何执行此操作。

@interface ViewController ()
@property (strong, nonatomic) UITextView *textView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.textView = [UITextView new];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.textView.frame = self.view.bounds;
    [self textViewDidChange:self.textView];
}

- (void)textViewDidChange:(UITextView *)textView {  
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.firstLineHeadIndent = 20.f;   
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:textView.text attributes:@{NSParagraphStyleAttributeName: style}];    
    textView.attributedText = string;
}
@end

【问题讨论】:

    标签: objective-c ios8 uitextview


    【解决方案1】:

    我认为这与您的代码的工作相同。

    textView.textContainerInset = UIEdgeInsetsMake(8.0f, 20.0f, 8.0f, 0.0f);
    

    【讨论】:

    • 我是缩进第一行而不是整个文本视图。
    • 您可以先将文本设置为空白空间,然后再删除该空间。
    • 我也想过这个问题,但是那个 hack 会导致我的项目出现问题。
    • 出于我的目的,我不能使用多余的字符进行布局。
    【解决方案2】:

    如果我理解正确,您希望光标在用户点击空的 UITextView 开始输入时缩进,而目前只有在用户开始输入时才开始缩进。

    在您的 viewDidLoad 中,使用 @" " 初始化属性文本,然后将文本设置为 @"",如下所示:

    -(void)viewDidLoad 
    {
        [super viewDidLoad];
        self.textView = [UITextView new];
        self.textView.delegate = self;
        [self.view addSubview:self.textView];
    
        NSMutableParagraphStyle* style = [NSMutableParagraphStyle new];
        style.firstLineHeadIndent = 20.f;   
        NSMutableAttributedString* string = [[NSMutableAttributedString alloc] initWithString:@" " attributes:@{NSParagraphStyleAttributeName: style}];    
        textView.attributedText = string;
        textView.text = @"";
    }
    

    注意:我认为textViewDidChange里面的代码是没有必要的。

    【讨论】:

    • 是的,但是正如我在我的 cmets 中为其他发布的答案所写的那样,我无法更改属性文本的值来简单地触发属性。我希望在您第一次点击带有空字符串的文本视图时发生缩进,就像您从键盘插入和删除字符时一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多