2016-11-29 191 views
1

我想知道是否有可能在文本视图中只显示3行文本,并且当您单击阅读更多按钮时,它将展开为包含超过3行文本的整个文本。这在Swift中如何实现,没有任何pod或插件?如何展开 - 在Swift中折叠UITextView?

谢谢。

+0

这可以帮助你 - http://stackoverflow.com/questions/38244707/simplest-way-to-implement-a-read-more-button-to-expand-a-uitextview-in-ios -swi – Santosh

+0

我不想使用外部库... – Caspert

+0

@Caspert你可以查看库,然后找出你想要使用的代码... –

回答

2

如果你想在不使用其他第三方库的情况下做到这一点,最简单的方法是调整你的UITextView的框架。在我的示例代码中,我的storyboard中有一个textView和一个Button。并在按下按钮时调用onReadMore。我只用40作为它的大小,当它被展开时为200。

class ViewController: UIViewController 
{ 
    @IBOutlet weak var textView: UITextView! 

    override func viewDidLoad() 
    { 
    super.viewDidLoad() 

    let frame = textView.frame 
    let newRect = CGRectMake(frame.origin.x, frame.origin.y, 200, 40) 
    textView.frame = newRect 
    } 

    @IBAction func onReadMore(sender: AnyObject) 
    { 
    let frame = textView.frame 

    if frame.height < 180 
    { 
     textView.frame = CGRectMake(frame.origin.x, frame.origin.y, 200, 180) 
    } 
    else 
    { 
     textView.frame = CGRectMake(frame.origin.x, frame.origin.y, 200, 40) 
    } 
    } 
} 
+0

如果展开的高度未知/动态,该怎么办? – Sneha

+0

你可以使用框架的高度作为基础,然后添加一个固定的数字。 –