UIT 텍스트 보기에서 텍스트를 세로로 가운데 배치
텍스트를 세로 방향으로 큰 내부에 배치합니다.UITextView화면 전체를 채웁니다. 그래서 텍스트가 거의 없을 때는 단어를 두어 개 말하면 높이에 따라 중앙에 위치합니다.텍스트(IB에서 찾을 수 있는 속성)를 중심화하는 것이 아니라 텍스트를 세로로 바로 가운데에 배치하는 것이 문제입니다.UITextView 텍스트가 짧아서 빈 공간이 없는 경우UITextView. 이거 할 수 있어요?
먼저 관찰자를 추가합니다.contentSize의 핵심 가치UITextView뷰가 로드된 경우:
- (void) viewDidLoad {
[textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
[super viewDidLoad];
}
그런 다음 이 메소드를 추가하여 조정합니다.contentOffset그 때마다contentSize값 변경:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
UIKit이 KVO를 준수하지 않기 때문에, 저는 이것을 하위 클래스로 구현하기로 결정했습니다.UITextView언제든지 업데이트 되는군요.contentSize변화들.
카를로스의 답변을 약간 변형한 것인데, 이는 다음과 같은 내용을 설정합니다.contentInset대신에contentOffset. iOS 9와 호환되는 것 외에도 iOS 8.4에서는 버그가 적은 것 같습니다.
class VerticallyCenteredTextView: UITextView {
override var contentSize: CGSize {
didSet {
var topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
topCorrection = max(0, topCorrection)
contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0)
}
}
}
KVO를 사용하지 않으려면 다음과 같은 기능으로 이 코드를 내보내면서 오프셋을 수동으로 조정할 수도 있습니다.
-(void)adjustContentSize:(UITextView*)tv{
CGFloat deadSpace = ([tv bounds].size.height - [tv contentSize].height);
CGFloat inset = MAX(0, deadSpace/2.0);
tv.contentInset = UIEdgeInsetsMake(inset, tv.contentInset.left, inset, tv.contentInset.right);
}
전화해서는
-(void)textViewDidChange:(UITextView *)textView{
[self adjustContentSize:textView];
}
코드의 텍스트를 편집할 때마다.컨트롤러를 위임자로 설정하는 것을 잊지 마십시오.
스위프트 3 버전:
func adjustContentSize(tv: UITextView){
let deadSpace = tv.bounds.size.height - tv.contentSize.height
let inset = max(0, deadSpace/2.0)
tv.contentInset = UIEdgeInsetsMake(inset, tv.contentInset.left, inset, tv.contentInset.right)
}
func textViewDidChange(_ textView: UITextView) {
self.adjustContentSize(tv: textView)
}
iOS 9.0.2의 경우 내용을 설정해야 합니다.대신 삽입.콘텐츠 오프셋을 KVO로 설정하면 iOS 9.0.2는 마지막 순간에 0으로 설정하여 콘텐츠 오프셋의 변경 사항을 덮어씁니다.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
UITextView *tv = object;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
[tv setContentInset:UIEdgeInsetsMake(topCorrect,0,0,0)];
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:NO];
[questionTextView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
}
왼쪽, 하단, 오른쪽 모서리 인셋에 각각 0, 0, 0을 사용했습니다.당신의 사용 사례에 대해서도 반드시 그것들을 계산해야 합니다.
사용하는 간단한 작업입니다.NSLayoutManager실제 텍스트 크기를 구하다NSTextContainer
class VerticallyCenteredTextView: UITextView {
override func layoutSubviews() {
super.layoutSubviews()
let rect = layoutManager.usedRect(for: textContainer)
let topInset = (bounds.size.height - rect.height) / 2.0
textContainerInset.top = max(0, topInset)
}
}
사용하지않습니다.contentSize그리고.contentInset당신의 마지막 계산에서.
여기.UITextView내용을 수직으로 중앙에 배치하는 확장:
extension UITextView {
func centerVertically() {
let fittingSize = CGSize(width: bounds.width, height: CGFloat.max)
let size = sizeThatFits(fittingSize)
let topOffset = (bounds.size.height - size.height * zoomScale) / 2
let positiveTopOffset = max(0, topOffset)
contentOffset.y = -positiveTopOffset
}
}
제약 조건만으로 직접 설정할 수 있습니다.
제약 조건에서 텍스트를 세로와 가로로 정렬하기 위해 추가한 제약 조건은 다음과 같이 세 가지입니다.
- 높이를 0으로 만들고 제약 조건을 다음보다 크게 추가합니다.
- 부모 제약 조건에 수직 정렬 추가
- 부모 제약 조건에 수평 정렬 추가
방금 Swift 3에서 사용자 지정 세로 중심 텍스트 뷰를 만들었습니다.
class VerticallyCenteredTextView: UITextView {
override var contentSize: CGSize {
didSet {
var topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
topCorrection = max(0, topCorrection)
contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0)
}
}
}
참조: https://geek-is-stupid.github.io/2017-05-15-how-to-center-text-vertically-in-a-uitextview/
func alignTextVerticalInTextView(textView :UITextView) {
let size = textView.sizeThatFits(CGSizeMake(CGRectGetWidth(textView.bounds), CGFloat(MAXFLOAT)))
var topoffset = (textView.bounds.size.height - size.height * textView.zoomScale) / 2.0
topoffset = topoffset < 0.0 ? 0.0 : topoffset
textView.contentOffset = CGPointMake(0, -topoffset)
}
자동 레이아웃 및 설정과 함께 사용하는 텍스트 보기가 있습니다.lineFragmentPadding그리고.textContainerInset◦ 도 제상황에서는 .위의 어떤 해결책도 제 상황에서는 통하지 않았습니다.하지만 저는 이 방법이 통합니다. 9 iOS 9로 완료트료로
@interface VerticallyCenteredTextView : UITextView
@end
@implementation VerticallyCenteredTextView
-(void)layoutSubviews{
[self recenter];
}
-(void)recenter{
// using self.contentSize doesn't work correctly, have to calculate content size
CGSize contentSize = [self sizeThatFits:CGSizeMake(self.bounds.size.width, CGFLOAT_MAX)];
CGFloat topCorrection = (self.bounds.size.height - contentSize.height * self.zoomScale) / 2.0;
self.contentOffset = CGPointMake(0, -topCorrection);
}
@end
저도 이 문제를 가지고 있고, 그것을 해결했습니다.UITableViewCell와 함께UITextView. 사용자 정의에서 메서드를 만들었습니다.UITableViewCell 클래스,스,성statusTextView:
- (void)centerTextInTextView
{
CGFloat topCorrect = ([self.statusTextView bounds].size.height - [self.statusTextView contentSize].height * [self.statusTextView zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
self.statusTextView.contentOffset = (CGPoint){ .x = 0, .y = -topCorrect };
그리고 이 방법을 메소드(method)라고 부릅니다.
- (void)textViewDidBeginEditing:(UITextView *)textView
- (void)textViewDidEndEditing:(UITextView *)textView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
이 솔루션은 문제없이 사용할 수 있었으니 사용해 보세요.
스위프트 3:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textField.frame = self.view.bounds
var topCorrect : CGFloat = (self.view.frame.height / 2) - (textField.contentSize.height / 2)
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect
textField.contentInset = UIEdgeInsetsMake(topCorrect,0,0,0)
}
Carlos 답변에 추가합니다. TV 크기보다 큰 텍스트가 있을 경우 텍스트를 최근화할 필요가 없으므로 다음 코드를 변경합니다.
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
다음 항목에 대해:
if ([tv contentSize].height < [tv bounds].size.height) {
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
자동 배치 솔루션:
- UITextView의 컨테이너 역할을 하는 UIView를 작성합니다.
- 다음 제약 조건을 추가합니다.
- 텍스트 보기:선행 공간 정렬 위치: 컨테이너
- 텍스트 보기:후행 공간 정렬: 컨테이너
- 텍스트 보기:중심 Y 정렬: 용기
- 텍스트 보기: 높이가 같음: 컨테이너, 관계: ≤
아래 코드를 사용해 볼 수 있습니다. 관찰자가 필수로 필요하지 않습니다.뷰가 할당 해제될 때 관찰자가 오류를 발생시키기도 합니다.이 코드를 보기 DidLoad, 보기 WillPear 또는 보기 DidPear로 유지할 수 있습니다.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^(void) {
UITextView *tv = txtviewDesc;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
});
});
저는 이렇게 했습니다. 우선 UIView에 UITextView를 내장했습니다(이것은 mac OS에서도 작동합니다).그런 다음 외부 UIView의 네 면을 모두 컨테이너 측면에 고정하여 UITextView와 유사하거나 동일한 모양과 크기를 제공했습니다.그래서 저는 UITextView를 위한 적절한 컨테이너를 가지고 있었습니다.그런 다음 UITextView의 좌우 테두리를 UIView의 측면에 고정하고 UITTextView에 높이를 부여했습니다.마지막으로 UIView에서 UITextView를 세로로 가운데에 두었습니다.빙고 :) 이제 UITtextView가 UIView에 수직으로 중심이 되므로 UITtextView 내부의 텍스트도 수직으로 중심이 됩니다.
UITextView+수직 정렬 .h
// UITextView+VerticalAlignment.h
// (c) The Internet 2015
#import <UIKit/UIKit.h>
@interface UITextView (VerticalAlignment)
- (void)alignToVerticalCenter;
- (void)disableAlignment;
@end
UITextView+수직 정렬.m
#import "UITextView+VerticalAlignment.h"
@implementation UITextView (VerticalAlignment)
- (void)alignToVerticalCenter {
[self addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
- (void)disableAlignment {
[self removeObserver:self forKeyPath:@"contentSize"];
}
@end
저는 이 문제를 중앙 높이까지 수직으로 확장하여 해결하였습니다.
스위프트 5:
extension UITextView {
func centerContentVertically() {
let fitSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
let size = sizeThatFits(fitSize)
let heightOffset = (bounds.size.height - size.height * zoomScale) / 2
let positiveTopOffset = max(0, heightOffset)
contentOffset.y = -positiveTopOffset
}
}
RubyMotion의 iOS10용 솔루션:
class VerticallyCenteredTextView < UITextView
def init
super
end
def layoutSubviews
self.recenter
end
def recenter
contentSize = self.sizeThatFits(CGSizeMake(self.bounds.size.width, Float::MAX))
topCorrection = (self.bounds.size.height - contentSize.height * self.zoomScale) / 2.0;
topCorrection = 0 if topCorrection < 0
self.contentInset = UIEdgeInsetsMake(topCorrection, 0, 0, 0)
end
end
언급URL : https://stackoverflow.com/questions/12591192/center-text-vertically-in-a-uitextview
'programing' 카테고리의 다른 글
| 사용자가 로그인할 때 update_at 열을 업데이트하는 방법은 무엇입니까? (0) | 2023.09.10 |
|---|---|
| 패치를 적용할 때 충돌을 해결할 수 있는 방법이 있습니까? (0) | 2023.09.10 |
| 종속 자식 이미지가 있는 도커 이미지를 삭제할 수 없습니다. (0) | 2023.09.10 |
| apt-add-repository: 명령을 찾을 수 없음 오류가 도커 파일에 있습니다. (0) | 2023.09.10 |
| Powershell을 사용하여 파일의 속성을 변경하려면 어떻게 해야 합니까? (0) | 2023.09.10 |

