简体   繁体   English

如何在UITextView中间垂直对齐文本

[英]How to align text vertically in middle in UITextView

I'm trying to align text in UITextView vertically in middle. 我正试图在中间垂直对齐UITextView中的文本。 After search I found code and it seems to work until we start to type and hit enter when cursor jumps. 搜索后,我找到了代码,它似乎工作,直到我们开始键入并在光标跳转时按Enter键。 When we hit enter key while typing inside text view the cursor jumps to adjust its position which I'm assuming due to the way it's called/implemented. 当我们在文本视图中键入内部时按下输入键时,光标会跳转以调整其位置,这是我所假设的,因为它被调用/实现的方式。

Is there a better and more elegant solution to this? 这有更好,更优雅的解决方案吗?

I've implemented it as UITextView extension. 我已将其实现为UITextView扩展。 This code is taken from one of the solutions suggested on Center text vertically in a UITextView 此代码取自UITextView中垂直中心文本上建议的解决方案之一

My question is to fix the jumping issue. 我的问题是解决跳跃问题。 It's not a duplicate of above question. 这不是上述问题的重复。

extension UITextView {
    func alignTextVerticallyInContainer() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = ((bounds.size.height - size.height * zoomScale) / 2)
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset + 1
    }
}

And calling it from 并从中调用它

override func viewDidLayoutSubviews() {
    textView.alignTextVerticallyInContainer()
}

请检查此链接以获取中心文本对齐方式。

 textView.textAlignment = .center

You can accomplish this with auto-layout only - no code needed. 您只需使用自动布局即可完成此操作 - 无需代码。

Start by adding a UIScrollView - I've constrained it to 80-pts from the Top, 20-pts on each side, and a Height constraint of 240 (I set the background to orange-is, to make it easy to see): 首先添加一个UIScrollView - 我将它限制在距离顶部80个点 ,每侧20个点 ,高度限制为240个 (我将背景设置为橙色,以便于查看):

在此输入图像描述

Next, add a standard UIView as a subview of the scrollView (I set the background to cyan to make it easy to see). 接下来,添加标准UIView作为scrollView的子视图(我将背景设置为青色以便于查看)。 Constrain it 8-pts on each side and on top and bottom (for a little padding). 在每侧以及顶部和底部约束8个点 (用于一点填充)。 Constrain its Width equal to the scrollView Width, with a constant of -16 (for the side padding), and constrain its Height equal to the scrollView Height, also with a constant of -16 (for the top/bottom padding). 将其宽度限制为等于scrollView Width,常量为-16 (对于边填充),并将其高度限制为等于scrollView高度,同时使用-16的常量(对于顶部/底部填充)。

Key point: set the Priority of the Height constraint to Low (250) . 关键点:设置高度约束的优先级低(250)。 That will allow it to grow when needed: 这将允许它在需要时增长:

在此输入图像描述

Now add a UITextView as a subview of the cyan view. 现在添加一个UITextView作为青色视图的子视图。 Start with only one line of text. 从一行文字开始。 Constrain it 8-pts from each side (for padding); 从每侧约束8个点 (用于填充); constrain it >= 8-pts on the Top and Bottom; 在顶部和底部限制它> = 8-pts ; and constrain it Centered Vertically in the span view: 并在跨度视图中将其限制为垂直居中

在此输入图像描述

When you run the app, it should function like this (again, no code needed): 当你运行应用程序时,它应该像这样运行(再次,不需要代码):

在此输入图像描述

在此输入图像描述

在此输入图像描述

Here is the source of the Storyboard: 以下是故事板的来源:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="LZe-dy-wRt">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="k3M-Zu-xX0">
            <objects>
                <viewController id="LZe-dy-wRt" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="fZP-6s-NIY">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="guO-HM-qxH">
                                <rect key="frame" x="20" y="100" width="335" height="240"/>
                                <subviews>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="zW5-KI-gna">
                                        <rect key="frame" x="8" y="8" width="319" height="224"/>
                                        <subviews>
                                            <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" text="Start with one line." textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="S6g-U0-TeD">
                                                <rect key="frame" x="8" y="95.5" width="303" height="33"/>
                                                <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                            </textView>
                                        </subviews>
                                        <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="S6g-U0-TeD" secondAttribute="bottom" constant="8" id="Ewc-yq-KHO"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="leading" secondItem="zW5-KI-gna" secondAttribute="leading" constant="8" id="RIE-gD-bX2"/>
                                            <constraint firstAttribute="trailing" secondItem="S6g-U0-TeD" secondAttribute="trailing" constant="8" id="SfV-e8-TXV"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="top" relation="greaterThanOrEqual" secondItem="zW5-KI-gna" secondAttribute="top" constant="8" id="byT-nx-8K1"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="centerY" secondItem="zW5-KI-gna" secondAttribute="centerY" id="qGs-hb-AdH"/>
                                        </constraints>
                                    </view>
                                </subviews>
                                <color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                <constraints>
                                    <constraint firstAttribute="bottom" secondItem="zW5-KI-gna" secondAttribute="bottom" constant="8" id="1xU-wS-Qcb"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="top" secondItem="guO-HM-qxH" secondAttribute="top" constant="8" id="CgB-kT-vjH"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="leading" secondItem="guO-HM-qxH" secondAttribute="leading" constant="8" id="O4I-aF-PEV"/>
                                    <constraint firstAttribute="height" constant="240" id="OZD-dD-yht"/>
                                    <constraint firstAttribute="trailing" secondItem="zW5-KI-gna" secondAttribute="trailing" constant="8" id="QXI-Lh-37A"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="height" secondItem="guO-HM-qxH" secondAttribute="height" priority="250" constant="-16" id="dMe-rS-ZOO"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="width" secondItem="guO-HM-qxH" secondAttribute="width" constant="-16" id="pGF-wL-V4q"/>
                                </constraints>
                            </scrollView>
                        </subviews>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <constraints>
                            <constraint firstItem="XpO-5d-W48" firstAttribute="trailing" secondItem="guO-HM-qxH" secondAttribute="trailing" constant="20" id="Mvu-Ug-NEY"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="leading" secondItem="XpO-5d-W48" secondAttribute="leading" constant="20" id="Rfe-Ev-3xj"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="top" secondItem="XpO-5d-W48" secondAttribute="top" constant="80" id="YhH-mc-af6"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="XpO-5d-W48"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="p5Q-GK-BKG" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-10" y="775"/>
        </scene>
    </scenes>
</document>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM