IT

둥근 사각형 텍스트 필드처럼 UITextview의 스타일을 지정하는 방법은 무엇입니까?

lottoking 2020. 5. 25. 22:20
반응형

둥근 사각형 텍스트 필드처럼 UITextview의 스타일을 지정하는 방법은 무엇입니까?


텍스트 작성기를 댓글 작성기로 사용하고 있습니다.

속성 관리자에서 테두리 스타일 속성과 같은 것을 찾을 수 없으므로 둥근 사각형을 사용할 수 있습니다 UITextField.

그래서, 질문은 : 나는 스타일을 어떻게 UITextView유사한을 UITextField둥근 RECT로?


선택할 암시 적 스타일은 없으며 QuartzCore프레임 워크를 사용하여 약간의 코드를 작성해야합니다 .

//first, you
#import <QuartzCore/QuartzCore.h>

//.....

//Here I add a UITextView in code, it will work if it's added in IB too
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 220, 200, 100)];

//To make the border look very close to a UITextField
[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[textView.layer setBorderWidth:2.0];

//The rounded corner part, where you specify your view's corner radius:
textView.layer.cornerRadius = 5;
textView.clipsToBounds = YES;

OS 3.0 이상에서만 작동하지만 지금은 사실상 플랫폼이라고 생각합니다.


이 코드는 나를 위해 잘 작동했습니다.

    [yourTextView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [yourTextView.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [yourTextView.layer setBorderWidth: 1.0];
    [yourTextView.layer setCornerRadius:8.0f];
    [yourTextView.layer setMasksToBounds:YES];

스위프트 3 버전

인터페이스 빌더에서 텍스트보기를 설정 한 후

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    textView.layer.cornerRadius = 5     
    textView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
    textView.layer.borderWidth = 0.5  
    textView.clipsToBounds = true
}

스위프트 2.2 버전

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    textView.layer.cornerRadius = 5     
    textView.layer.borderColor = UIColor.grayColor().colorWithAlphaComponent(0.5).CGColor
    textView.layer.borderWidth = 0.5  
    textView.clipsToBounds = true
}

편집 : 가져와야합니다

#import <QuartzCore/QuartzCore.h>

코너 반경을 사용합니다.

이것을 시도하십시오 그것은 확실히 작동합니다

UITextView* txtView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
txtView.layer.cornerRadius = 5.0;
txtView.clipsToBounds = YES;

Rob이 테두리 색상을 비슷하게 설정 UITextField하려면 다음 줄을 추가하여 테두리 너비를 2.0으로 변경하고 색상을 회색으로 변경 해야하는 경우

[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]]; 
[textView.layer setBorderWidth:2.0];

나는 실제 거래를 원했기 때문에 UIImageView의 하위보기로 추가 했습니다 UITextView. UITextField위에서 아래로의 그라디언트를 포함하여 의 기본 테두리와 일치합니다 .

textView.backgroundColor = [UIColor clearColor];
UIImageView *borderView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height)];
borderView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UIImage *textFieldImage = [[UIImage imageNamed:@"TextField.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 8, 15, 8)];
borderView.image = textFieldImage;
[textField addSubview: borderView];
[textField sendSubviewToBack: borderView];

내가 사용하는 이미지는 다음과 같습니다.

여기에 이미지 설명을 입력하십시오 여기에 이미지 설명을 입력하십시오


한 가지 해결책은 UITextView 아래에 UITextField추가 하고 UITextView배경을 투명하게 만들고에 대한 사용자 상호 작용을 비활성화하는 것 UITextField입니다. 그런 다음 코드에서 UITextField프레임을 다음과 같이 변경하십시오.

self.textField.frame = CGRectInset(self.textView.frame, 0, -2);

텍스트 필드와 모양이 정확히 같습니다.

Jon이 제안한 것처럼 이 코드 조각 [UIViewController viewDidLayoutSubviews]을 iOS 5.0 이상에 넣어야합니다 .


최상의 효과를 얻으려면 사용자 정의 (신축 가능한) 배경 이미지를 사용해야합니다. 이것 UITextField의 둥근 테두리가 그려지 는 방식이기도합니다 .


프로그래밍 없이이 작업을 수행 한 방법은 텍스트 필드 배경을 투명하게 만든 다음 그 뒤에 둥근 사각형 버튼을 배치하는 것입니다. 버튼 설정을 변경하여 비활성화하고 Disable adjusts image확인란의 선택을 취소하십시오 .


DCKit 이라는 내 라이브러리를 확인하고 싶을 수도 있습니다 .

다음에서 직접 둥근 모서리 텍스트보기 (및 텍스트 필드 / 단추 / 평야 UIView)를 만들 수 Interface Builder있습니다.

DCKit : 경계 UITextView

또한 유효성 검사가 포함 된 텍스트 필드, 테두리가있는 컨트롤, 점선 테두리, 원 및 헤어 라인보기와 같은 다른 유용한 기능이 많이 있습니다.


I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.

The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119

// This class implements a UITextView that has a UITextField behind it, where the 
// UITextField provides the border.
//
class TextView : UITextView, UITextViewDelegate
{
    var textField = TextField();

    required init?(coder: NSCoder)
    {
        fatalError("This class doesn't support NSCoding.")
    }

    override init(frame: CGRect, textContainer: NSTextContainer?)
    {
        super.init(frame: frame, textContainer: textContainer);

        self.delegate = self;

        // Create a background TextField with clear (invisible) text and disabled
        self.textField.borderStyle = UITextBorderStyle.RoundedRect;
        self.textField.textColor = UIColor.clearColor();
        self.textField.userInteractionEnabled = false;

        self.addSubview(textField);
        self.sendSubviewToBack(textField);
    }

    convenience init()
    {
        self.init(frame: CGRectZero, textContainer: nil)
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }

    // UITextViewDelegate - Note: If you replace delegate, your delegate must call this
    func scrollViewDidScroll(scrollView: UIScrollView)
    {
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }        
}

One way I found to do it without programming is to make the textfield background transparent, then place a Round Rect Button behind it. Make sure to change the button settings to disable it and uncheck the Disable adjusts image checkbox.

Tried the Quartzcore code and found it caused lag on my old 3G (I use for testing). Not a big issue but if you want to be as inclusive as possible for different ios and hardware I recommend Andrew_L's answer above - or make your own images and apply accordingly.


There is a great background image that is identical to the UITextView used for sending text messages in iPhone's Messages app. You'll need Adobe Illustrator to get & modify it. iphone ui vector elements


#import <QuartzCore/QuartzCore.h>
- (void)viewDidLoad{
  UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 220, 200, 100)];
  textView.layer.cornerRadius = 5;
  textView.clipsToBounds = YES;
  [textView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
  [textView.layer setBorderColor: [[UIColor grayColor] CGColor]];
  [textView.layer setBorderWidth: 1.0];
  [textView.layer setCornerRadius:8.0f];
  [textView.layer setMasksToBounds:YES];
  [self.view addSubView:textview];
}

You can create a Text Field that doesn't accept any events on top of a Text View like this:

CGRect frameRect = descriptionTextField.frame;
frameRect.size.height = 50;
descriptionTextField.frame = frameRect;
descriptionTextView.frame = frameRect;
descriptionTextField.backgroundColor = [UIColor clearColor];
descriptionTextField.enabled = NO;
descriptionTextView.layer.cornerRadius = 5;
descriptionTextView.clipsToBounds = YES;

If you want to keep your controller code clean, you can subclass UITextView like below, and change the class name in the Interface Builder.

RoundTextView.h

#import <UIKit/UIKit.h>
@interface RoundTextView : UITextView
@end

RoundTextView.m

#import "RoundTextView.h"
#import <QuartzCore/QuartzCore.h>
@implementation RoundTextView
-(id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.333] CGColor]];
        [self.layer setBorderWidth:1.0];
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;
    }
    return self;
}
@end

I don't think that it is possible. but you can do UITableView(grouped) with 1 section and 1 empty cell and use it as a container for your UITextView.


This is an old question, and I was also searched for this questions answer. luvieeres' answer is 100% correct and later Rob added some code. That is excellent, but I found a third party in another questions answer which seems very helpful to me. I was not only searched for similar look of UITextField over UITextView, I was also searched for multiline support. ChatInputSample satisfied both. Thats why I think this third party might be helpful to others. Also thanks to Timur, he mentioned this open source in here.


In iOS7 the following matches UITextField border perfectly (to my eye at least):

textField.layer.borderColor = [[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor];
textField.layer.borderWidth = 0.5;
textField.layer.cornerRadius = 5;
textField.clipsToBounds = YES;

There is no need to import anything special.

Thanks to @uvieere and @hanumanDev whose answers go me almost there :)


Here is my solution:

- (void)viewDidLoad {
    [super viewDidLoad];


    self.textView.text = self.messagePlaceholderText;
    self.textView.layer.backgroundColor = [[UIColor whiteColor] CGColor];
    self.textView.layer.borderColor = [[[UIColor grayColor] colorWithAlphaComponent:0.3] CGColor];
    self.textView.layer.borderWidth = 0.5;
    self.textView.layer.cornerRadius = 5.5f;
    self.textView.layer.masksToBounds = YES;
    self.textView.textColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    if (textView == self.tvMessage) {
        // Delete placeholder text
        if ([self.textView.text isEqualToString:self.messagePlaceholderText]) {
            self.textView.text = @"";
            self.textView.textColor = [UIColor blackColor];
        }
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView == self.tvMessage) {
        // Write placeholder text
        if (self.textView.text.length == 0) {
            self.textView.text = self.messagePlaceholderText;
            self.textView.textColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        }
    }
}

How about just:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 280, 32)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:textField];

참고 URL : https://stackoverflow.com/questions/1824463/how-to-style-uitextview-to-like-rounded-rect-text-field

반응형