我想在与 API 数据相对应的标签中将可用时间显示为粗体和不可用时间(删除线)

问题描述 投票:0回答:1

enter image description here

对于当天(全天时间不同,周日休息)和日期的API数据,获取进入时间和离开时间,由此将可用时间中的标签更改为粗体,并删除不可用时间。

进入时间前所有时间均不可用,离开后所有时间均不可用,午餐时间也不可用。

如何将API数据的条件写入标签更改(加粗/删除线)?

API响应:

 Optional(<__NSSingleObjectArrayI 0x600003873050>(
 {
  day = Saturday;
  dArray = "<null>";
  enteringTime = "09.00 am";
  entryTime = "<null>";
  exitTime = "<null>";
  id = 13;
  leavingTime = "06.00 pm";
  lunchtimeFrom = "13:00";
  lunchtimeTo = "14:00";
 }

代码片段:

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "08:05 AM") 

attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) 

time805Lbl.attributedText = attributeString
ios swift if-statement conditional-statements
1个回答
1
投票

在您的

viewController
-

中定义日期格式
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

现在,添加一个检查可用时间的方法

func checkAvailableTime(currentTime: String) -> NSMutableAttributedString {

    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: currentTime)

    var time = "\(times["lunchtimeFrom"]!)"
    let lunchStartTime = dateFormatter.date(from: time)

    time = "\(times["lunchtimeTo"]!)"
    let lunchEndTime = dateFormatter.date(from: time)


    let personCheckTime = dateFormatter.date(from: currentTime)


    if  (lunchStartTime!.compare(personCheckTime!) == .orderedAscending) && (lunchEndTime!.compare(personCheckTime!) == .orderedDescending){

        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
    }

    return attributeString
}

是时候调用该方法了 -

time805Lbl.attributedText = checkAvailableTime(currentTime: time805Lbl.text!)

其中

times
是您的时间响应。 我希望您能得到如下回复 -

let times = [
    "day":"Saturday",
    "dArray":"<null>",
    "enteringTime":"09:00 AM",
    "entryTime":"<null>",
    "exitTime":"<null>",
    "id": 13,
    "leavingTime":"06:00 PM",
    "lunchtimeFrom":"1:00 PM",
    "lunchtimeTo":"2:00 PM"
    ] as [String : Any]

如果您仍有任何问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.