2015-01-12 74 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) 
} 

如何做到這一點的任何建議,將不勝感激。

編輯:只是解決你如何解開你的可選,加載一個字符串和追加一個路徑組件,並沒有必要使用自我。

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

你要設置在屏幕中間的文本不管文本有多長? – 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水平居中你的TextView的約束。不過在Interface Builder和Storyboard中這樣做更容易。

如果你不想使用約束(支持iOS 5中,下),你可以使用autoresizingMasks爲TextView的是這樣的:

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

對不起,說沒有幫助的情況下。我已將新代碼添加到上述問題中。 – martin

相關問題