整个星期我都在尝试让 UITextView 调整大小。我看不出这应该如何完成,所以我决定包括几乎所有相关代码。
我有这个对话 View :
这个对话 View 是一个 UIViewController,里面有一个 UITableView(使用约束)。我有一个自定义的 UIView 子类 ConversationToolbar 设置为 inputAccessoryView (包含它的 UIViewController 可以成为第一响应者,所以该 View 始终可见),其中包含 2 个 subview 。一个用于 UITextView 和左右按钮,一个用于表情符号。表情符号仅在点击左按钮时显示:
选择一个时,它以 float 标签显示:
当使用多行时,我现在无法调整此 UITextView 的大小。我曾尝试自己计算所有帧,但这似乎以某种奇怪的方式与我的约束相冲突。几乎总是 UITextView 要么太小,要么只有在我按下另一个键更新 View 后它才会调整大小。或者 UITextView 在键盘上方变大,或者在关闭键盘时滑出 View 。
我已经从我的代码中删除了所有调整大小的功能,我想知道我需要做什么才能进行此调整。
在我的 ConversationViewController 中:
var toolbar: ConversationToolbar!
override var inputAccessoryView: UIView! {
get {
if toolbar == nil {
toolbar = NSBundle.mainBundle().loadNibNamed("ConversationToolbar", owner: nil, options: nil).last! as ConversationToolbar
toolbar.frame.size = CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 80)
toolbar.delegate = self
toolbar.setDraft(conversation.draft)
}
return toolbar
}
}
ConversationToolbar.xib 为:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6254" systemVersion="14D87p" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6247"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB" customClass="ConversationToolbar" customModule="Heaven_Help" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="s5O-PN-dtz">
<rect key="frame" x="0.0" y="554" width="600" height="46"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" horizontalCompressionResistancePriority="749" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="pbw-hg-sNn">
<rect key="frame" x="0.0" y="0.0" width="36" height="46"/>
<inset key="contentEdgeInsets" minX="8" minY="0.0" maxX="8" maxY="0.0"/>
<state key="normal" title="?">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="emoPress:" destination="iN0-l3-epB" eventType="touchUpInside" id="hLw-rH-Hym"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Vid-Ac-jz3">
<rect key="frame" x="548" y="0.0" width="52" height="46"/>
<inset key="contentEdgeInsets" minX="8" minY="0.0" maxX="8" maxY="0.0"/>
<state key="normal" title="Send">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="sendPress:" destination="iN0-l3-epB" eventType="touchUpInside" id="rzU-Vk-nJa"/>
</connections>
</button>
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Czv-f6-jOP">
<rect key="frame" x="36" y="8" width="512" height="30"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
</textView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="height" constant="46" id="D1D-QM-5n2"/>
<constraint firstAttribute="trailing" secondItem="Vid-Ac-jz3" secondAttribute="trailing" id="H9Y-xT-aqe"/>
<constraint firstAttribute="centerY" secondItem="pbw-hg-sNn" secondAttribute="centerY" id="IYf-5R-S97"/>
<constraint firstItem="Czv-f6-jOP" firstAttribute="leading" secondItem="pbw-hg-sNn" secondAttribute="trailing" id="LpH-ir-M9U"/>
<constraint firstAttribute="centerY" secondItem="Vid-Ac-jz3" secondAttribute="centerY" id="NQ1-m1-9rk"/>
<constraint firstAttribute="bottom" secondItem="Vid-Ac-jz3" secondAttribute="bottom" id="UUt-1r-emN"/>
<constraint firstItem="Czv-f6-jOP" firstAttribute="top" secondItem="s5O-PN-dtz" secondAttribute="top" constant="8" id="VWB-7N-LrK"/>
<constraint firstAttribute="bottom" secondItem="Czv-f6-jOP" secondAttribute="bottom" constant="8" id="WTi-8a-kaM"/>
<constraint firstItem="pbw-hg-sNn" firstAttribute="leading" secondItem="s5O-PN-dtz" secondAttribute="leading" id="a4Q-W4-ROh"/>
<constraint firstAttribute="bottom" secondItem="pbw-hg-sNn" secondAttribute="bottom" id="hGG-Xe-FZZ"/>
<constraint firstItem="Vid-Ac-jz3" firstAttribute="leading" secondItem="Czv-f6-jOP" secondAttribute="trailing" id="jc6-18-MYq"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="rh6-cD-U1e">
<rect key="frame" x="0.0" y="508" width="600" height="46"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</view>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="6zz-GF-eHs">
<rect key="frame" x="279" y="525" width="42" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="centerX" secondItem="6zz-GF-eHs" secondAttribute="centerX" id="3at-fx-ZCR"/>
<constraint firstAttribute="bottom" secondItem="s5O-PN-dtz" secondAttribute="bottom" id="3r5-GG-6Eo"/>
<constraint firstItem="s5O-PN-dtz" firstAttribute="height" secondItem="rh6-cD-U1e" secondAttribute="height" id="MBP-k2-Qre"/>
<constraint firstItem="s5O-PN-dtz" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="PLK-DE-38r"/>
<constraint firstItem="s5O-PN-dtz" firstAttribute="top" secondItem="6zz-GF-eHs" secondAttribute="bottom" constant="8" symbolic="YES" id="PRr-qQ-oyf"/>
<constraint firstAttribute="trailing" secondItem="s5O-PN-dtz" secondAttribute="trailing" id="PqA-VB-NxV"/>
<constraint firstItem="s5O-PN-dtz" firstAttribute="top" secondItem="rh6-cD-U1e" secondAttribute="bottom" id="ZxJ-8p-Mjq"/>
<constraint firstItem="rh6-cD-U1e" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="lsS-5I-Saq"/>
<constraint firstAttribute="trailing" secondItem="rh6-cD-U1e" secondAttribute="trailing" id="yRP-hS-dpr"/>
</constraints>
<connections>
<outlet property="emoButton" destination="pbw-hg-sNn" id="VJx-J0-hBJ"/>
<outlet property="emoLabel" destination="6zz-GF-eHs" id="pUW-yD-pIq"/>
<outlet property="emoView" destination="rh6-cD-U1e" id="0YV-Wx-clp"/>
<outlet property="sendButton" destination="Vid-Ac-jz3" id="6FV-Q2-ufA"/>
<outlet property="textSuperView" destination="s5O-PN-dtz" id="BIT-bH-p4M"/>
<outlet property="textView" destination="Czv-f6-jOP" id="syf-v4-LLy"/>
</connections>
</view>
</objects>
</document>
最后是我的 ConversationToolbar.swift:
import Foundation
class ConversationToolbar: UIView, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var emoView: UIView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var textSuperView: UIView!
@IBOutlet weak var emoButton: UIButton!
@IBOutlet weak var emoLabel: UILabel!
var delegate: ConversationToolbarDelegate!
var emobuttons: [String: UIButton]!
var emoSelected: String?
var clickableSend: Bool {
get {
return ((delegate?.hasEnoughCredits() ?? false) && !(textView?.text?.isEmpty ?? true)) ?? false
}
}
override func awakeFromNib() {
textView.delegate = self
sendButton.enabled = clickableSend
self.autoresizingMask = .FlexibleHeight
// Make textView pretty
textView.backgroundColor = UIColor.whiteColor() // (white: 250/255, alpha: 1)
textView.font = UIFont.systemFontOfSize(17)
textView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 205/255, alpha:1).CGColor
textView.layer.borderWidth = 0.5
textView.layer.cornerRadius = 5
textView.scrollsToTop = false
textView.textContainerInset = UIEdgeInsetsMake(4, 3, 3, 3)
textView.autoresizingMask = .FlexibleHeight
// Add a nice border to the view
textSuperView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 205/255, alpha:1).CGColor
textSuperView.layer.borderWidth = 0.5
textSuperView.backgroundColor = UIColor(white: 235/255, alpha: 1)
textSuperView.autoresizingMask = .FlexibleHeight
// Prettify emoView
emoView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 205/255, alpha:1).CGColor
emoView.layer.borderWidth = 0.5
emoView.backgroundColor = UIColor(white: 235/255, alpha: 1)
// Emobar setup
emobuttons = StaticData.getEmoButtons()
let unusedSpace = UIScreen.mainScreen().bounds.width - emobuttons.sum {
button in
return button.intrinsicContentSize().width
}
let spaceBetweenButtons = Int(unusedSpace) / (emobuttons.count + 1)
var visualLayout = "H:|"
for button in emobuttons {
button.1.setTranslatesAutoresizingMaskIntoConstraints(false)
visualLayout += "-(space)-[\(button.0)]"
emoView.addSubview(button.1)
button.1.addTarget(self, action: "emoChosen:", forControlEvents: .TouchUpInside)
}
emoView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("\(visualLayout)-(space)-|", options: .AlignAllCenterY, metrics: ["space":spaceBetweenButtons], views: emobuttons))
emoView.addConstraint(NSLayoutConstraint(item: emoView, attribute: .CenterY, relatedBy: .Equal, toItem: emobuttons.values.array.first!, attribute: .CenterY, multiplier: 1, constant: 0))
// Prettify toolbar itself
self.backgroundColor = UIColor.clearColor()
// start hidden
emoView.hidden = true
emoLabel.hidden = emoSelected == nil
}
@IBAction func emoPress(sender: UIButton) {
emoView.hidden = !emoView.hidden
updateEmoLabel()
if !emoView.hidden {
emoLabel.hidden = true
}
}
@IBAction func sendPress(sender: UIButton) {
delegate.sendMessage(textView.text, feeling: emoSelected)
textView.text = ""
emoSelected = nil
sendButton.enabled = false
textViewDidChange(textView)
updateEmoLabel()
}
func emoChosen(sender: UIButton) {
emoView.hidden = true
emoSelected = sender.titleLabel?.text == "?" ? nil : sender.titleLabel?.text
updateEmoLabel()
}
func setDraft(draft: String) {
textView.text = draft
}
func updateEmoLabel() {
emoLabel.text = emoSelected
emoLabel.hidden = emoSelected == nil
}
/// MARK: UITextFieldDelegate
func textViewDidChange(textView: UITextView) {
sendButton.enabled = clickableSend
}
}
protocol ConversationToolbarDelegate {
func sendMessage(text: String, feeling: String?)
func hasEnoughCredits() -> Bool
}
最佳答案
我已经用 AutoLayout 解决了这个问题。我添加了一个新的约束来定义我的 UITextField 的高度,我正在 textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText 文本:String) -> Bool:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let oldHeight = textView.frame.height
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
let newSize = (newText as NSString).boundingRectWithSize(CGSize(width: textView.frame.width - textView.textContainerInset.right - textView.textContainerInset.left - 10, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font], context: nil)
let heightChange = newSize.height + textView.textContainerInset.top + textView.textContainerInset.bottom + 2.719 - oldHeight
textFieldHeightLayoutConstraint.constant += heightChange
return true
}
我遇到的问题是我将 AutoLayout 和 UIView.frame 设置为不同的设置,这导致它们发生冲突。
我是个白痴。
关于ios - 调整 inputAccessoryView 中文本字段的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28983113/
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
英文版英文链接关注公众号在“亚特兰蒂斯的回声”中踏上一段难忘的冒险之旅,深入未知的海洋深处。足智多谋的考古学家AriaSeaborne偶然发现了一件古代神器,揭示了一张通往失落之城亚特兰蒂斯的隐藏地图。在她神秘的导师内森·兰登教授的指导和勇敢的冒险家亚历克斯·默瑟的帮助下,阿丽亚开始了一段危险的旅程,以揭开这座传说中城市的真相。他们的冒险之旅带领他们穿越险恶的大海、神秘的岛屿和充满陷阱和谜语的致命迷宫。随着Aria潜在的魔法能力的觉醒,她被睿智勇敢的QueenNeria的幻象所指引,她让她为即将到来的挑战做好准备。三人组揭开亚特兰蒂斯令人惊叹的隐藏文明,并了解到邪恶的巫师马拉卡勋爵试图利用其古
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
Region是HBase数据管理的基本单位,region有一点像关系型数据的分区。region中存储这用户的真实数据,而为了管理这些数据,HBase使用了RegionSever来管理region。Region的结构hbaseregion的大小设置默认情况下,每个Table起初只有一个Region,随着数据的不断写入,Region会自动进行拆分。刚拆分时,两个子Region都位于当前的RegionServer,但处于负载均衡的考虑,HMaster有可能会将某个Region转移给其他的RegionServer。RegionSplit时机:当1个region中的某个Store下所有StoreFile
我在一段非常简单的代码(如我所想)中得到了一个错误的值:org=4caseorgwhenorg=4val='H'endputsval=>nil请不要生气,我希望我错过了一些非常明显的东西,但我真的想不通。谢谢。 最佳答案 这是典型的Ruby错误。case有两种被调用的方法,一种是你传递一个东西作为分支的基础,另一种是你不传递的东西。如果您确实在case中指定了一个表达式语句然后评估所有其他条件并与===进行比较.在这种情况下org评估为false和org===false显然不是真的。所有其他情况也是如此,它们要么是真的,要么是假的。
我有以下内容:text.gsub(/(lower)(upper)/,'\1\2')我可以将\2替换为大写吗?类似于:sed-e's/\(abc\)/\U\1/'这在Ruby中可行吗? 最佳答案 查看gsub文档:str.gsub(模式){|匹配|block}→new_str在block形式中,当前匹配字符串作为参数传入,$1、$2、$`、$&、$'等变量将被适当设置。block返回的值将替换为每次调用的匹配项。"alowerupperb".gsub(/(lower)(upper)/){|s|$1+""+$2.upcase}
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visitthehelpcenter.关闭9年前。我正在创建一个Sinatra应用程序,它采用上传的CSV文件并将其内容放入哈希中。当我像这样在我的app.rb中引用这个散列时:hash=extract_values(path_to_filename)我不断收到此错误消息:undefinedmethod`bytesize'forHash:0x007fc5e28f2b90#object_idfile:utils.rblocation:bytesiz