2015-01-12 11 views
1

프로그래밍 방식으로 내보기에 UITextView를 추가했지만 화면의 세로 가운데에 텍스트를 설정하는 방법을 알 수 없습니다.Swift - 프로그래밍 방식으로 UITextView 중앙에 넣기

내 코드는 다음과 같습니다

var textView: UITextView? 
textView = UITextView(frame: view.bounds) 

if let theTextView = textView{ 

    let blurEffect = UIBlurEffect(style: .Dark) 
    let blurView = UIVisualEffectView(effect: blurEffect) 
    blurView.frame.size = CGSize(width: self.view.frame.width, height: self.view.frame.height) 
    blurView.center = view.center 
    blurView.tag = 1 

    theTextView.text = NSString(contentsOfFile: NSTemporaryDirectory() + "\(fileRef).txt", encoding: NSUTF8StringEncoding, error: nil) as String 
    theTextView.font = UIFont.systemFontOfSize(16) 
    theTextView.tag = 2 
    theTextView.textColor = UIColor.whiteColor() 
    theTextView.insertSubview(blurView, atIndex: 0) 
    theTextView.textAlignment = NSTextAlignment.Center 
    view.addSubview(theTextView) 
} 

이 작업을 수행하는 방법에 대한 어떤 제안을 감상 할 수있다.

EDIT : 선택 사항을 언랩하고 String을로드하고 경로 구성 요소를 추가해야하는 방법을 수정하여 자체를 사용할 필요가 없습니다.

var textView: UITextView? 
textView = UITextView(frame: UIScreen.mainScreen().bounds) 
if let textView = textView { 
    let verticalCenter = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0) 
    let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) 
    blurView.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) 
    blurView.center = view.center 
    blurView.tag = 1 
    textView.font = UIFont.systemFontOfSize(16) 
    textView.tag = 2 
    textView.text = String(contentsOfURL: NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("\(fileRef).txt"))!, encoding: NSUTF8StringEncoding, error: nil) 
    textView.textColor = UIColor.whiteColor() 
    textView.insertSubview(blurView, atIndex: 0) 
    textView.textAlignment = .Center 
    view.addSubview(textView) 
    view.addConstraint(verticalCenter) 
} 
+1

당신은 화면의 중앙에 텍스트를 설정하려면 : 당신이 제약 조건을 사용하지 않으려면

,이 같은 텍스트 뷰에 대한 autoresizingMasks을 사용할 수 있습니다 (아이폰 OS 5 낮은를 지원하는) 텍스트의 길이가 아무리 길어도? – gabbler

+0

@ gabbler 예, 코드의 다른 부분에 얼마나 오래있을 수 있는지 제한되었습니다. – martin

+0

내가 올바르게 당신을 이해했는지 확인하는 것, 화면/부모보기의 상단에서 하단으로 평등 한 공간 형태와 같이 수직 중간을 의미합니까? – Emil

답변

0

당신은 다음과 같은 제약 조건을 추가하여이에 대한 자동 레이아웃을 사용할 수 있습니다

let verticalCenter = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0) 
self.view.addConstraint(verticalCenter) 

이것은 self.view 내에서 수평으로 텍스트 뷰를 중심으로 제약 조건을 추가합니다. Interface Builder와 Storyboard에서 훨씬 쉽게 할 수 있습니다.

textView.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin 
+0

유감스럽게도 그건 도움이되지 못했습니다. 위 질문에 새 코드를 추가했습니다. – martin