Как выровнять текст по центру по вертикали в UITextView - PullRequest
0 голосов
/ 29 мая 2019

Я пытаюсь выровнять текст в UITextView по вертикали в середине. После поиска я нашел код, и он, кажется, работает, пока мы не начнем печатать и нажимать ввод, когда курсор прыгает. Когда мы нажимаем клавишу ввода при вводе текста в текстовом представлении, курсор перемещается, чтобы отрегулировать его положение, которое я предполагаю из-за способа его вызова / реализации.

Есть ли лучшее и более элегантное решение для этого?

Я реализовал это как расширение UITextView. Этот код взят из одного из решений, предложенных для Центрирование текста по вертикали в UITextView

Мой вопрос - исправить проблему с прыжками. Это не дубликат вышеуказанного вопроса.

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

И звоню с

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

Ответы [ 2 ]

0 голосов
/ 31 мая 2019

Это можно сделать только с помощью автоматического макета - код не требуется.

Начните с добавления UIScrollView - я ограничил его 80-пунктов сверху, 20-пунктов с каждой стороны и ограничением высоты 240 (я установил фон оранжевым, чтобы его было легче видеть):

enter image description here

Затем добавьте стандарт UIView в качестве подпредставления scrollView (я установил фон в голубой цвет, чтобы его было легко увидеть). Ограничьте его 8-pts с каждой стороны, сверху и снизу (для небольшого отступа). Ограничьте его ширину, равную ширине scrollView, с константой -16 (для бокового заполнения), и ограничьте его высоту, равную высоте scrollView, также с константой -16 (для верхнего / нижнего отступа).

Ключевой момент: установите Приоритет ограничения высоты на Низкий (250) . Это позволит ему расти при необходимости:

enter image description here

Теперь добавьте UITextView как подпредставление голубого представления. Начните только с одной строки текста. Ограничьте его 8-pts с каждой стороны (для заполнения); ограничить его > = 8 пунктов сверху и снизу; и ограничить его Вертикально по центру в виде пролета:

enter image description here

Когда вы запускаете приложение, оно должно работать следующим образом (опять же, код не нужен):

enter image description here

enter image description here

enter image description here

Вот источник Раскадровки:

<?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>
0 голосов
/ 29 мая 2019

Пожалуйста, проверьте эту ссылку для выравнивания текста по центру.

 textView.textAlignment = .center
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...