How to set content inset for UITextView in ios
Asked Answered
R

2

39

I'm having a UITextView and set content inset as

[atextView setContentInset:UIEdgeInsetsMake(0, 10, 0, 0)];

This code working in iOS 6.1 and below, but nothing happens in iOS 7.0.

Ragen answered 28/9, 2013 at 10:4 Comment(4)
Is there a way to do this IN STORYBOARD ?!Yarn
did you tried updated answer?Ragen
Yes there is , check my solution below Joe BlowFind
@BencePattogato thanks for the update.Ragen
R
140

got answer:

[atextView  setTextContainerInset:UIEdgeInsetsMake(7, 7, 0, 0)];

fixed my problem.

And in Swift...

@IBOutlet var tv:UITextView!
override func awakeFromNib() {
    super.awakeFromNib()
    tv.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

UPDATE: another option to do that.

UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[msgtext setLeftViewMode:UITextFieldViewModeAlways];
[msgtext setLeftView:spacerView];
Ragen answered 28/9, 2013 at 10:16 Comment(8)
hey @murugha23 , I need you help on how you solved textview setContentInset problem in IOS7Jab
replace setTextContainerInset instead of setContentInset. If you want to provide previous versions of ios, then check a condition reg., current device system versionRagen
it would be good if you can provide me a sample code of your class,including keyboard and textview's various methods ,so i can I have clear ideaJab
actually whats your problem ? is it setting improperly or completely not setting?Ragen
Yes I am posting question and posting link soonJab
Note that you should only use one or the other. Using both together will result in undesirable additive behavior.Leon
before using above code i will check condition for ios versionRagen
What I've discovered is that there is some odd (buggy) interaction between the setTextContainerInset UIEdgeInsets values. I was able to get the behavior I wanted as discussed here: stackoverflow.com/questions/19422578 I'd recommend (blindly) messing around with the 4 values to try and find an acceptable behavior.Undeceive
F
0

An alternative and maybe a little more convenient way to do it, by subclassing the UITextField and add an @IBInspectable inset property.

import UIKit

class UITextfieldWithInset: UITextField {

    @IBInspectable
    var textfieldInset: CGPoint = CGPointMake(0, 0)

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

}
Find answered 26/5, 2016 at 16:52 Comment(1)
This is a nice answer for UITextField, but the question is about UITextViewDorman

© 2022 - 2024 — McMap. All rights reserved.