簡體   English   中英

Swift-以編程方式將UITextView居中

[英]Swift - Centering the UITextView programmatically

我已經以編程方式將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)
}

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

編輯:剛剛解決了如何解開可選項,加載String並追加路徑組件的問題,而無需使用self。

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)
}

您可以通過添加以下約束來使用“自動布局”:

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)

這將添加一個約束,使textView在self.view水平居中。 不過,這在Interface Builder和Storyboard中更容易實現。

如果您不想使用約束(以支持iOS 5及更低版本),則可以對autoresizingMasks使用autoresizingMasks ,如下所示:

textView.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM