【问题标题】:Animation not working when constraint is changed together with alpha约束与 alpha 一起更改时动画不起作用
【发布时间】:2020-05-22 02:15:48
【问题描述】:

在一个表格视图单元格中,我有一个文本视图,它的大小既减小了又随着 alpha 消失。

//self is tableviewcell
self.hiddenCon.isActive = true  //this is a contraint of the textview, making it smaller
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
UIView.animate(withDuration: 0.25) {
        self.textview.alpha = 0 //I also want to make it disappear while going smaller
        self.layoutIfNeeded()
}

但它最终会变小,但没有 alpha 变化

【问题讨论】:

  • 为什么要给self.layoutIfNeeded()打两次电话?
  • 试试这个: UIView.animate(withDuration: 0.25) { self.hiddenCon.isActive = true self.textview.alpha = 0 //我也想让它在变小的时候消失 self.layoutIfNeeded( ) }
  • 看起来问题只考虑 UITextView。只要您想更改 UITextView 的 alpha 及其框架,那么它的行为就会不正确。是否将 UITextView 包装到某个 UIView 并更改其 alpha 并不重要。只有一个快速修复方法是不更改 UITextView 的框架,而只更改超级视图包装器的框架。它不会是完美的,但可能已经足够好了。
  • @Rob 很公平,这里找不到示例项目github.com/dpyy/tabletest.git

标签: ios animation autolayout uikit


【解决方案1】:

您也许可以按照自己的方式解决问题,但是...

我建议您对文本视图使用单个 Height 约束,而不是激活第二个约束(您没有显示停用 showingCon 约束的位置),并更改 @ 987654326@值...

这是一个对我有用的非常基本的示例:

import UIKit

class ShrinkTextViewCell: UITableViewCell {

    @IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet var theTextView: UITextView!

    var tableUpdateCallback: (()->())?

    @IBAction func didTap(_ sender: Any) {

        if theTextView.alpha > 0.0 {

            UIView.animate(withDuration: 0.5) {
                self.theTextView.alpha = 0.0
                self.textViewHeightConstraint.constant = 0
                self.contentView.layoutIfNeeded()
                self.tableUpdateCallback?()
            }

        } else {

            UIView.animate(withDuration: 0.5) {
                self.theTextView.alpha = 1.0
                self.textViewHeightConstraint.constant = 128
                self.contentView.layoutIfNeeded()
                self.tableUpdateCallback?()
            }

        }
    }

}

class ShrinkTextViewTableViewController: UITableViewController {

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let c = tableView.dequeueReusableCell(withIdentifier: "ShrinkTextViewCell", for: indexPath) as! ShrinkTextViewCell
        c.tableUpdateCallback = {
            tableView.beginUpdates()
            tableView.endUpdates()
        }
        return c

    }
}

这里是故事板的来源:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="9iy-6q-gap">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Shrink Text View Table View Controller-->
        <scene sceneID="oHl-Pu-bIJ">
            <objects>
                <tableViewController id="wSO-s3-dB0" customClass="ShrinkTextViewTableViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
                    <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="WtR-bt-uSy">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <prototypes>
                            <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="ShrinkTextViewCell" rowHeight="189" id="gZx-b8-Hf3" customClass="ShrinkTextViewCell" customModule="scratchy" customModuleProvider="target">
                                <rect key="frame" x="0.0" y="28" width="375" height="189"/>
                                <autoresizingMask key="autoresizingMask"/>
                                <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="gZx-b8-Hf3" id="xmG-jI-EeI">
                                    <rect key="frame" x="0.0" y="0.0" width="375" height="189"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <subviews>
                                        <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="CGL-ug-wBr">
                                            <rect key="frame" x="16" y="11" width="240" height="128"/>
                                            <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                            <constraints>
                                                <constraint firstAttribute="width" constant="240" id="Dip-pf-MUH"/>
                                                <constraint firstAttribute="height" priority="999" constant="128" id="mK2-jh-d1y"/>
                                            </constraints>
                                            <string key="text">Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.</string>
                                            <color key="textColor" systemColor="labelColor" cocoaTouchSystemColor="darkTextColor"/>
                                            <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                            <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                        </textView>
                                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vto-8g-NOW">
                                            <rect key="frame" x="313" y="11" width="46" height="30"/>
                                            <color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                            <state key="normal" title="Button"/>
                                            <connections>
                                                <action selector="didTap:" destination="gZx-b8-Hf3" eventType="touchUpInside" id="4nC-JL-rWD"/>
                                            </connections>
                                        </button>
                                    </subviews>
                                    <constraints>
                                        <constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="vto-8g-NOW" secondAttribute="bottom" id="5P3-E0-KJV"/>
                                        <constraint firstItem="CGL-ug-wBr" firstAttribute="leading" secondItem="xmG-jI-EeI" secondAttribute="leadingMargin" id="6C9-8M-fUa"/>
                                        <constraint firstItem="vto-8g-NOW" firstAttribute="top" secondItem="xmG-jI-EeI" secondAttribute="topMargin" id="Fwc-nY-zK8"/>
                                        <constraint firstAttribute="trailingMargin" secondItem="vto-8g-NOW" secondAttribute="trailing" id="Gfq-Ps-hxG"/>
                                        <constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="CGL-ug-wBr" secondAttribute="bottom" id="PFA-sR-BPk"/>
                                        <constraint firstItem="CGL-ug-wBr" firstAttribute="top" secondItem="xmG-jI-EeI" secondAttribute="topMargin" id="vyi-D5-OSn"/>
                                    </constraints>
                                </tableViewCellContentView>
                                <connections>
                                    <outlet property="textViewHeightConstraint" destination="mK2-jh-d1y" id="jgg-nH-KJ0"/>
                                    <outlet property="theTextView" destination="CGL-ug-wBr" id="GRu-g4-TPK"/>
                                </connections>
                            </tableViewCell>
                        </prototypes>
                        <connections>
                            <outlet property="dataSource" destination="wSO-s3-dB0" id="hW0-YN-O65"/>
                            <outlet property="delegate" destination="wSO-s3-dB0" id="S0F-gf-dAv"/>
                        </connections>
                    </tableView>
                    <navigationItem key="navigationItem" id="HhZ-lH-fRh"/>
                </tableViewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="S7z-u4-GiE" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="357.60000000000002" y="2048.7256371814096"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="PyK-HU-aub">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="9iy-6q-gap" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="M2B-qr-tr5">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="wSO-s3-dB0" kind="relationship" relationship="rootViewController" id="ghB-H0-NIB"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="AAD-E1-PrO" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-581.60000000000002" y="2048.7256371814096"/>
        </scene>
    </scenes>
</document>

输出如下:

当您点击每个单元格中的按钮时,该单元格中的文本视图将“缩小并淡出”或“增长并淡入”。

【讨论】:

  • 我将您的代码复制并粘贴到一个测试项目中,它也有同样的问题。文本视图消失。我在项目中看到的唯一两个区别是它位于堆栈视图中,并且操作来自 didSelect 而不是按钮。完整的测试项目在这里github.com/dpyy/tabletest.git
  • @erotsppa - 嗯....你使用了我的故事板源吗?我相信问题是因为您在UITextView 上禁用了滚动。重新启用滚动,看看你会得到什么。
  • 也许它的行为会根据 ios 版本和模拟器或设备而有所不同。
  • @LukášMareda - 不,问题是启用/禁用滚动。如果我们给文本视图一个背景色,并将动画持续时间设置为 1.5(又好又慢,所以我们可以观看它)... 滚动 dis 启用 text 消失,而文本 view 缩小和淡化。 UITextView 有一个 .textContainer 对象,它定义了显示文本的区域。 那个 对象正在“捕捉”到新的高度。离开滚动 enabled 可以解决这个问题。
  • 也可以通过禁用滚动来清楚地演示,然后将文本视图的高度缩小到 20。我们看到 .textContainer 捕捉到新的高度,然后观察 文本视图收缩和淡入淡出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2012-09-17
相关资源
最近更新 更多